Example usage for java.net URL openConnection

List of usage examples for java.net URL openConnection

Introduction

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

Prototype

public URLConnection openConnection() throws java.io.IOException 

Source Link

Document

Returns a java.net.URLConnection URLConnection instance that represents a connection to the remote object referred to by the URL .

Usage

From source file:com.zuora.api.UsageAdjInvoiceRegenerator.java

public static void main(String[] args) {

    String exportIdPRPC, exportIdII, exportFileIdII, exportFileIdPRPC, queryII, queryPRPC;

    boolean hasArgs = false;
    if (args != null && args.length >= 1) {
        UsageAdjInvoiceRegenerator.PROPERTY_FILE_NAME = args[0];
        hasArgs = true;/*  w  w w  . j  a v  a2  s .co m*/
    }
    AppParamManager.initParameters(hasArgs);
    if (!AppParamManager.TASK_ID.equals("")) {
        try {
            zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME,
                    AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION);

            zApiClient.login();
        } catch (Exception ex) {
            Logger.print(ex);
            Logger.print("RefreshSession - There's exception in the API call.");
        }

        queryPRPC = AppParamManager.PRPCexportQuery;
        queryII = AppParamManager.IIexportQuery;

        exportIdPRPC = zApiClient.createExport(queryPRPC);

        exportIdII = zApiClient.createExport(queryII);

        // ERROR createExport fails
        if (exportIdII == null || exportIdII.equals("")) {
            Logger.print("Error. Failed to create Invoice Item Export");
            //return false;
        }

        // ERROR createExport fails
        if (exportIdPRPC == null || exportIdPRPC.equals("")) {
            Logger.print("Error. Failed to create PRPC export");
            //return false;
        }

        exportFileIdII = zApiClient.getExportFileId(exportIdII);

        if (exportFileIdII == null) {
            Logger.print("Error. Failed to get Invoice Item Export file Id");
            //log.closeLogFile();
            //return false;
        }

        exportFileIdPRPC = zApiClient.getExportFileId(exportIdPRPC);

        if (exportFileIdPRPC == null) {
            Logger.print("Error. Failed to get PRPC Export file Id");
            //log.closeLogFile();
            //return false;
        }
        // get the export file from zuora
        //zApiClient.getFile(exportFileIdII, exportFileIdTI);

        /*
        Logger.print("II export ID: "+exportFileIdII);
        Logger.print("TI export ID: "+exportFileIdTI);
        */

        Logger.print("Opening Export file");

        //Base64 bs64 = new BASE64Encoder();
        /*
        String login = AppParamManager.USER_NAME+":"+AppParamManager.USER_PASSWORD;
        String authorization ="Basic "+ Base64.encodeBase64String(login.getBytes());
        String zendpoint = "";
        */

        String authorization = "";
        //Base64 bs64 = new BASE64Encoder();
        if (AppParamManager.USER_SESSION.isEmpty()) {
            String login = AppParamManager.USER_NAME + ":" + AppParamManager.USER_PASSWORD;
            authorization = "Basic " + Base64.encodeBase64String(login.getBytes());
        } else {
            authorization = "ZSession " + AppParamManager.USER_SESSION;
        }
        String zendpoint = "";

        try {

            /*
            if( AppParamManager.API_URL.contains("api") ){
               //look in api sandbox
               zendpoint = "https://apisandbox.zuora.com/apps/api/file/";
            } else {
               //look in production
               zendpoint = "https://www.zuora.com/apps/api/file/";
            }
            */

            int index = AppParamManager.API_URL.indexOf("apps");
            index = index + 5;
            zendpoint = AppParamManager.API_URL.substring(0, index) + "api/file/";
            Logger.print(zendpoint);

            //zendpoint = AppParamManager.FILE_URL;

            //Start reading Invoice Items

            String zendpointII = zendpoint + exportFileIdII + "/";

            URL url = new URL(zendpointII);
            URLConnection uc = url.openConnection();
            //Logger.print("Opening invoice item file: "+exportFileIdII+" authorization: "+authorization);
            uc.setRequestProperty("Authorization", authorization);

            InputStream content = (InputStream) uc.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            CSVReader cvsReader = new CSVReader(in);

            List<String[]> batchOfRawDataList = null;

            while ((batchOfRawDataList = cvsReader.parseEntity()) != null) {
                UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(),
                        "InvoiceItem");
            }

            in.close();

            String zenpointPRPC = zendpoint + exportFileIdPRPC + "/";
            url = new URL(zenpointPRPC);
            uc = url.openConnection();
            uc.setRequestProperty("Authorization", authorization);
            content = (InputStream) uc.getInputStream();
            in = new BufferedReader(new InputStreamReader(content));
            cvsReader = new CSVReader(in);

            while ((batchOfRawDataList = cvsReader.parseEntity()) != null) {
                UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(),
                        "PRPCItem");
            }

            in.close();
            Logger.print("start processing values");

            UsageAdjInvoiceRegenerator chargeAdjustment = new UsageAdjInvoiceRegenerator();
            int[] results;
            int totalErrors = 0;
            String emailmsg = "";
            Logger.print("----------------------------------------");
            Logger.print("start creating usages");
            results = zApiClient.createUsageItems(newUsageCollection);
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage creation ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start cancelling invoices");
            results = zApiClient.alterInvoices(newUsageCollection, "cancel");
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice cancellation ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start deleting usages");
            results = zApiClient.deleteUsageItems(deleteList);
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage deletion ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start regenerating invoices");
            results = zApiClient.alterInvoices(newUsageCollection, "generate");
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice generation ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start deleting old invoices");
            results = zApiClient.alterInvoices(newUsageCollection, "delete");
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice deletion ";
            }
            totalErrors = totalErrors + results[1];

            // Create the attachment
            EmailAttachment attachment = new EmailAttachment();
            if (totalErrors > 0) {

                String logFileName = AppParamManager.OUTPUT_FOLDER_LOCATION + File.separator + "runtime_log_"
                        + AppParamManager.OUTPUT_FILE_POSTFIX + ".txt";

                attachment.setPath(logFileName);
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setDescription("System Log");
                attachment.setName("System Log");
            }

            MultiPartEmail email = new MultiPartEmail();
            email.setSmtpPort(587);
            email.setAuthenticator(
                    new DefaultAuthenticator(AppParamManager.EMAIL_ADDRESS, AppParamManager.EMAIL_PASSWORD));
            email.setDebug(false);
            email.setHostName("smtp.gmail.com");
            email.setFrom("zuora@gmail.com");

            if (totalErrors > 0) {
                email.setSubject("Base Calc Processor Finished with Errors");
                email.setMsg("The base calc processing has finished " + emailmsg + "records successfully.");
            } else {
                email.setSubject("Base Calc Processor Finished Successfully");
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice ";
                email.setMsg("The base calc processing has finished " + emailmsg + "records successfully.");
            }
            email.setTLS(true);
            email.addTo(AppParamManager.RECIPIENT_ADDRESS);
            if (totalErrors > 0) {
                email.attach(attachment);
            }
            email.send();
            System.out.println("Mail sent!");
            if (hasArgs) {
                Connection conn = AppParamManager.getConnection();
                Statement stmt = conn.createStatement();
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                java.util.Date date = new Date();
                stmt.executeUpdate("UPDATE TASK SET STATUS = 'completed', END_TIME = '"
                        + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID);
                Utility.saveLogToDB(conn);
                conn.close();
            }

        } catch (Exception e) {
            Logger.print("Failure, gettingFile.");
            Logger.print("Error getting the export file: " + e.getMessage());
            //System.out.println("Error getting the export file: "+e.getMessage());
            try {
                Connection conn = AppParamManager.getConnection();
                Statement stmt = conn.createStatement();
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                java.util.Date date = new Date();
                stmt.executeUpdate("UPDATE TASK SET STATUS = 'failed', END_TIME = '" + dateFormat.format(date)
                        + "' WHERE ID = " + AppParamManager.TASK_ID);
                Utility.saveLogToDB(conn);
                conn.close();
            } catch (Exception e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
        }
    } else {
        Logger.print("No tasks in wait status");
    }
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args/*ww w.ja v a2s  .c  o  m*/
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Parameters: xml_url image_url");
        return;/* www .j a v  a  2 s .  c o m*/
    }

    java.net.URL xml_url;
    try {
        xml_url = new java.net.URL(args[0]);
    } catch (Exception e) {
        jlogger.log(Level.INFO, "Error building xmlurl, will prefix file://", e);

        xml_url = new java.net.URL("file://" + args[0]);
    }

    java.net.URL image_url;
    try {
        image_url = new java.net.URL(args[1]);
    } catch (Exception e) {
        jlogger.log(Level.INFO, "Error building xmlurl, will prefix file://", e);

        image_url = new java.net.URL("file://" + args[1]);
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(xml_url.openStream());
    // Element instruction = (Element)
    // doc.getElementsByTagNameNS("http://www.occamlab.com/te/parsers",
    // "ImageParser").item(0);
    Element instruction = (Element) doc.getDocumentElement();

    PrintWriter logger = new PrintWriter(System.out);
    InputStream image_is = image_url.openConnection().getInputStream();

    Document result = parse(image_is, instruction, logger);
    logger.flush();

    if (result != null) {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            tf.setAttribute("http://saxon.sf.net/feature/strip-whitespace", "all");
        } catch (IllegalArgumentException e) {
            jlogger.log(Level.INFO, "setAttribute(\"http://saxon.sf.net/feature/strip-whitespace\", \"all\");",
                    e);

        }
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.transform(new DOMSource(result), new StreamResult(System.out));
    }

    System.exit(0);
}

From source file:ru.apertum.qsystem.client.forms.FAdmin.java

/**
     * @param args the command line arguments
     * @throws Exception//  ww w. ja va  2s.c o  m
     */
    public static void main(String args[]) throws Exception {
        QLog.initial(args, 3);
        Locale.setDefault(Locales.getInstance().getLangCurrent());

        //?  ? , ? 
        final Thread tPager = new Thread(() -> {
            FAbout.loadVersionSt();
            String result = "";
            try {
                final URL url = new URL(PAGER_URL + "/qskyapi/getpagerdata?qsysver=" + FAbout.VERSION_);
                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("User-Agent", "Java bot");
                conn.connect();
                final int code = conn.getResponseCode();
                if (code == 200) {
                    try (BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), "utf8"))) {
                        String inputLine;
                        while ((inputLine = in.readLine()) != null) {
                            result += inputLine;
                        }
                    }
                }
                conn.disconnect();
            } catch (Exception e) {
                System.err.println("Pager not enabled. " + e);
                return;
            }
            final Gson gson = GsonPool.getInstance().borrowGson();
            try {
                final Answer answer = gson.fromJson(result, Answer.class);
                forPager = answer;
                if (answer.getData().size() > 0) {
                    forPager.start();
                }
            } catch (Exception e) {
                System.err.println("Pager not enabled but working. " + e);
            } finally {
                GsonPool.getInstance().returnGson(gson);
            }
        });
        tPager.setDaemon(true);
        tPager.start();

        Uses.startSplash();
        //     plugins
        Uses.loadPlugins("./plugins/");
        //      ?.
        FLogin.logining(QUserList.getInstance(), null, true, 3, FLogin.LEVEL_ADMIN);
        Uses.showSplash();
        java.awt.EventQueue.invokeLater(() -> {
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                        .getInstalledLookAndFeels()) {
                    System.out.println(info.getName());
                    /*Metal Nimbus CDE/Motif Windows   Windows Classic  //GTK+*/
                    if ("Windows".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
                if ("/".equals(File.separator)) {
                    final FontUIResource f = new FontUIResource(new Font("Serif", Font.PLAIN, 10));
                    final Enumeration<Object> keys = UIManager.getDefaults().keys();
                    while (keys.hasMoreElements()) {
                        final Object key = keys.nextElement();
                        final Object value = UIManager.get(key);
                        if (value instanceof FontUIResource) {
                            final FontUIResource orig = (FontUIResource) value;
                            final Font font1 = new Font(f.getFontName(), orig.getStyle(), f.getSize());
                            UIManager.put(key, new FontUIResource(font1));
                        }
                    }
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                    | UnsupportedLookAndFeelException ex) {
            }
            try {
                form = new FAdmin();
                if (forPager != null) {
                    forPager.showData(false);
                } else {
                    form.panelPager.setVisible(false);
                }
                form.setVisible(true);
            } catch (Exception ex) {
                QLog.l().logger().error(" ? ??  . ", ex);
            } finally {
                Uses.closeSplash();
            }
        });
    }

From source file:GetURLInfo.java

/** Use the URLConnection class to get info about the URL */
public static void printinfo(URL url) throws IOException {
    URLConnection c = url.openConnection(); // Get URLConnection from URL
    c.connect(); // Open a connection to URL

    // Display some information about the URL contents
    System.out.println("  Content Type: " + c.getContentType());
    System.out.println("  Content Encoding: " + c.getContentEncoding());
    System.out.println("  Content Length: " + c.getContentLength());
    System.out.println("  Date: " + new Date(c.getDate()));
    System.out.println("  Last Modified: " + new Date(c.getLastModified()));
    System.out.println("  Expiration: " + new Date(c.getExpiration()));

    // If it is an HTTP connection, display some additional information.
    if (c instanceof HttpURLConnection) {
        HttpURLConnection h = (HttpURLConnection) c;
        System.out.println("  Request Method: " + h.getRequestMethod());
        System.out.println("  Response Message: " + h.getResponseMessage());
        System.out.println("  Response Code: " + h.getResponseCode());
    }//from   w  w  w.  j  a  v  a 2 s.c o  m
}

From source file:Main.java

public static String getURLContent(String urlStr) throws Exception {
    URL url = new URL(urlStr);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);// w w  w  .  j  av a2  s .  c  o m
    connection.connect();
    OutputStream ous = connection.getOutputStream();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ous));
    bw.write("index.htm");
    bw.flush();
    bw.close();

    printRequestHeaders(connection);
    InputStream ins = connection.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(ins));
    StringBuffer sb = new StringBuffer();
    String msg = null;
    while ((msg = br.readLine()) != null) {
        sb.append(msg);
        sb.append("\n"); // Append a new line
    }
    br.close();
    return sb.toString();
}

From source file:Main.java

public static Bitmap downloadImage(String urlStr) throws IOException {
    URL url = new URL(urlStr);
    URLConnection connection = url.openConnection();
    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
    Bitmap result = BitmapFactory.decodeStream(bis);
    bis.close();//from ww w  . j  ava  2s.c  o  m
    return result;
}

From source file:Main.java

private static InputStream retrieve(String url) throws IOException {
    URL target = new URL(url);
    URLConnection connection = target.openConnection();
    return connection.getInputStream();
}

From source file:Main.java

public static InputStream HandlerData(String url) {
    InputStream inStream = null;/*from   w w  w.j  a  v a  2 s  . co  m*/

    try {
        URL feedUrl = new URL(url);
        URLConnection conn = feedUrl.openConnection();
        conn.setConnectTimeout(10 * 1000);
        inStream = conn.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return inStream;
}

From source file:Main.java

public static HttpsURLConnection parseURLConnection(String urlString) throws IOException {
    URL url = new URL(urlString);
    urlConnection = (HttpsURLConnection) url.openConnection();

    return urlConnection;
}