Example usage for java.net HttpURLConnection setFollowRedirects

List of usage examples for java.net HttpURLConnection setFollowRedirects

Introduction

In this page you can find the example usage for java.net HttpURLConnection setFollowRedirects.

Prototype

public static void setFollowRedirects(boolean set) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

Usage

From source file:org.apigw.authserver.ServerRunning.java

public Statement apply(final Statement base, FrameworkMethod method, Object target) {

    // Check at the beginning, so this can be used as a static field
    if (assumeOnline) {
        Assume.assumeTrue(serverOnline.get(port));
    } else {//  www.ja v a2s  . c o  m
        Assume.assumeTrue(serverOffline.get(port));
    }

    RestTemplate client = new RestTemplate();
    boolean followRedirects = HttpURLConnection.getFollowRedirects();
    HttpURLConnection.setFollowRedirects(false);
    boolean online = false;
    try {
        client.getForEntity(getUrl("/apigw-auth-server-web/login.jsp").toString(), String.class);
        online = true;
        logger.info("Basic connectivity test passed");
    } catch (RestClientException e) {
        logger.warn(String.format(
                "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
                port), e);
        if (assumeOnline) {
            Assume.assumeNoException(e);
        }
    } finally {
        HttpURLConnection.setFollowRedirects(followRedirects);
        if (online) {
            serverOffline.put(port, false);
            if (!assumeOnline) {
                Assume.assumeTrue(serverOffline.get(port));
            }

        } else {
            serverOnline.put(port, false);
        }
    }

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            postForStatus("/apigw-auth-server-web/login.jsp", new LinkedMultiValueMap<String, String>());
            base.evaluate();
        }
    };

}

From source file:org.zend.sdklib.internal.target.ZendDevCloud.java

/**
 * Uploads public key /*from w  w w .ja va 2 s.com*/
 * @return null on success, or an error message otherwise
 * @throws IOException 
 * @throws SdkException 
 * @throws JSONException 
 */
public void uploadPublicKey(String token, String container, String publicKey) throws SdkException {
    final boolean orginal = setFollowRedirect();
    SSLContextInitializer.instance.setDefaultSSLFactory();

    try {
        String text;
        try {
            text = doUploadKey(token, container, publicKey);
        } catch (IOException e) {
            throw new SdkException("Connection error, while uploading public key to target", e);
        }

        String status;
        String message;
        try {
            final JSONObject json = new JSONObject(text);
            status = (String) json.get("status");
            message = (String) json.get("message");
        } catch (JSONException ex) {
            throw new RuntimeException("Invalid JSON response from target", ex);
        }

        if (!"Success".equals(status)) {
            throw new SdkException(message);
        }

    } finally {
        HttpURLConnection.setFollowRedirects(orginal);
        SSLContextInitializer.instance.restoreDefaultSSLFactory();
    }
}

From source file:org.apache.hadoop.hdfs.TestHftpFileSystem.java

private void testDataNodeRedirect(Path path) throws IOException {
    // Create the file
    if (hdfs.exists(path)) {
        hdfs.delete(path, true);//w  w w .j a  v a 2s. c o  m
    }
    FSDataOutputStream out = hdfs.create(path, (short) 1);
    out.writeBytes("0123456789");
    out.close();

    // Get the path's block location so we can determine
    // if we were redirected to the right DN.
    BlockLocation[] locations = hdfs.getFileBlockLocations(path, 0, 10);
    String xferAddr = locations[0].getNames()[0];

    // Connect to the NN to get redirected
    URL u = hftpFs.getNamenodeURL("/data" + ServletUtil.encodePath(path.toUri().getPath()), "ugi=userx,groupy");
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    HttpURLConnection.setFollowRedirects(true);
    conn.connect();
    conn.getInputStream();

    boolean checked = false;
    // Find the datanode that has the block according to locations
    // and check that the URL was redirected to this DN's info port
    for (DataNode node : cluster.getDataNodes()) {
        DatanodeRegistration dnR = DataNodeTestUtils.getDNRegistrationForBP(node, blockPoolId);
        if (dnR.getXferAddr().equals(xferAddr)) {
            checked = true;
            assertEquals(dnR.getInfoPort(), conn.getURL().getPort());
        }
    }
    assertTrue("The test never checked that location of " + "the block and hftp desitnation are the same",
            checked);
}

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

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

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

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

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

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

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

From source file:org.zend.sdklib.internal.target.ZendDevCloud.java

/**
 * Detects the containers installed in Zend DevPaas given the username and
 * password properties//  w  ww.  j a va  2s  .  c om
 * 
 * @param username
 * @param password
 * @return the targets as captured by Zend DevPaas
 * @throws Exception
 */
public IZendTarget[] detectTarget(String username, String password, String privateKey)
        throws SdkException, IOException {

    final boolean orginal = setFollowRedirect();
    SSLContextInitializer.instance.setDefaultSSLFactory();

    try {
        // authenticate
        final String token = authenticate(username, password);

        // list
        String[] targets = listContainers(token);

        // info
        return createZendTargets(token, targets, privateKey);

    } finally {
        HttpURLConnection.setFollowRedirects(orginal);
        SSLContextInitializer.instance.restoreDefaultSSLFactory();
    }
}

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

public FetcherService() {
    super(FetcherService.class.getSimpleName());
    HttpURLConnection.setFollowRedirects(true);
    mHandler = new Handler();
}

From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * Constructor/*from   w  w w  .  jav  a  2  s.com*/
 *
 * @param host the host of the BOSH director
 * @param port the port of the BOSH director (usually 25555)
 * @param username the BOSH user used to log in
 * @param password the BOSH password used to log in
 */
public BoshClientImpl(String host, int port, String username, String password) {
    super();
    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;
    disableSSLChecks();
    HttpURLConnection.setFollowRedirects(false); // We do not want to follow redirects
}

From source file:dssat.WeatherFileSystem.java

public String WriteToFile(String wthFileName) {

    // prepare the file name from the organization name and the site index number and then write to that file
    String orgName = incache.get("Farm");
    String siteIndex = incache.get("SiteIndex");
    String finalOutputPath = readAttribute("DssatFolder");
    finalOutputPath = finalOutputPath + "\\" + readAttribute("Crop");

    File file = new File(finalOutputPath + dirseprator + wthFileName);

    String writeBuffer = null;//  w  ww.  j  a va 2 s. co  m

    PrintWriter pr = null;
    try {
        file.createNewFile();
        pr = new PrintWriter(file);
        writeBuffer = new String("*WEATHER : \n");
        pr.println(writeBuffer);
        writeBuffer = new String("@ INSI      LAT     LONG  ELEV   TAV   AMP REFHT WNDHT");
        pr.println(writeBuffer);

        double latitude = -34.23;
        double longitude = -34.23;
        double elevation = -99;
        double tavg = -99;
        double tamp = -99;
        double tmht = -99;
        double wmht = -99;

        writeBuffer = new String();
        //Empty 2 Char, Org 2 Char, Site 2Char, Space 1 Char, latitude 8Chars with 3 dec
        writeBuffer = String.format(
                "%.2s%.2s%.2s%.1s%8.3f%.1s%8.3f%.1s%5.0f%.1s%5.1f%.1s%5.1f%.1s%5.1f%.1s%5.1f", "  ", orgName,
                siteIndex, " ", latitude, " ", longitude, " ", elevation, " ", tavg, " ", tamp, " ", tmht, " ",
                wmht);
        pr.println(writeBuffer);

        int julianday = 56001;
        double solarrad = -99;
        double tmax = -99;
        double tmin = -99;
        double rain = -99;
        double dewp = -99;
        double wind = -99;
        double par = -99;

        writeBuffer = new String("@DATE  SRAD  TMAX  TMIN  RAIN  RHUM  WIND  TDEW  PAR");
        pr.println(writeBuffer);
        writeBuffer = new String();

        URL url = null;
        InputStream is = null;
        Integer plantingyear;
        if (incache.get("PlantingYear") != null) {
            plantingyear = Integer.parseInt(incache.get("PlantingYear"));
        } else {
            Date d = new Date();
            plantingyear = d.getYear() + 1900;
        }
        /*Bring the Weather details for last 10 Years and write the details to the WTH File. */
        try {

            String query = new String("SELECT%20*%20FROM%20FAWN_historic_daily_20140212%20"
                    + "WHERE%20(%20yyyy%20BETWEEN%20" + (plantingyear - 10) + "%20AND%20"
                    + plantingyear.toString() + ")" + "%20AND%20(%20LocId%20=%20"
                    + incache.get("StationLocationId") + ")" + "%20ORDER%20BY%20yyyy%20DESC%20");

            String urlStr = "http://abe.ufl.edu/bmpmodel/xmlread/rohit.php?sql=" + query;

            System.out.println("********************************");
            System.out.println(urlStr);

            //System.out.println(urlStr);
            URL uflconnection = new URL(urlStr);
            HttpURLConnection huc = (HttpURLConnection) uflconnection.openConnection();
            HttpURLConnection.setFollowRedirects(false);
            huc.setConnectTimeout(15 * 1000);
            huc.setRequestMethod("GET");
            huc.connect();
            InputStream input = huc.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                if (!(inputLine.startsWith("S") || inputLine.startsWith("s"))) {
                    String[] fields = inputLine.split(",");

                    int M = Integer.parseInt(fields[3]);
                    int D = Integer.parseInt(fields[4]);
                    int a = (14 - M) / 12;
                    int y = Integer.parseInt(fields[2]) + 4800 - a;
                    int m = M + 12 * a - 3;

                    long JD = D + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;

                    String tempDate = String.format("%05d",
                            Integer.parseInt(fields[2].substring(2)) * 1000 + Integer.parseInt(fields[5]));
                    String SRad;
                    if (fields[13].length() > 1) {
                        SRad = String.format("%.1f", Double.parseDouble(fields[13]));
                    } else {
                        SRad = "";
                    }
                    String TMax = String.format("%.1f", Double.parseDouble(fields[9]));
                    String TMin = String.format("%.1f", Double.parseDouble(fields[8]));
                    String RAIN = String.format("%.1f", Double.parseDouble(fields[12]));
                    String RHUM = String.format("%.1f", Double.parseDouble(fields[11]));
                    String WIND = String.format("%.1f", Double.parseDouble(fields[14]));
                    String TDEW = String.format("%.1f", Double.parseDouble(fields[10]));
                    String PAR = "";

                    String line = String.format("%5s %5s %5s %5s %5s %5s %5s %5s", tempDate, SRad, TMax, TMin,
                            RAIN, RHUM, WIND, TDEW);
                    pr.println(line);

                }
            }
            in.close();
            //System.out.println("Created teh connection successfully");

        } catch (MalformedURLException me) {
            me.printStackTrace();
            //return 21.4;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        if (pr != null) {
            pr.close();
        }
    }

    // Here I need to read all the data from the controls and write the data to the files. 
    for (int i = 0; i < incache.size(); i++) {

    }
    return file.getAbsolutePath();
}

From source file:com.adito.core.CoreServlet.java

/**
 * Constructor/*w  w  w .  jav a  2 s  . c o m*/
 */
public CoreServlet() {
    super();
    instance = this;
    pageScripts = new ArrayList<CoreScript>();
    coreEventService = new CoreEventServiceImpl();
    NavigationManager.addMenuTree(new CoreMenuTree());
    NavigationManager.addMenuTree(new PageTaskMenuTree());
    NavigationManager.addMenuTree(new ToolBarMenuTree());
    NavigationManager.addMenuTree(new NavigationBar());
    NavigationManager.addMenuTree(new TableItemActionMenuTree());
    Configuration.setConfiguration(new CoreJAASConfiguration());
    addTileConfigurationFile("/WEB-INF/tiles-defs.xml");

    // Make sure that Http redirects are followed in places where we use URL
    // to connect to our website
    HttpURLConnection.setFollowRedirects(true);

}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Perform an HTTP GET request against the URL.
 * @return the string response from the server
 *//*from   w  w  w  . ja  v  a2  s.  c  o m*/
public byte[] getBytes() throws IOException {
    if (connection == null) {
        if (proxy == null)
            connection = (HttpURLConnection) url.openConnection();
        else
            connection = (HttpURLConnection) url.openConnection(proxy);
    }

    prepareConnection(connection);

    connection.setDoOutput(false);
    connection.setRequestMethod("GET");

    HttpURLConnection.setFollowRedirects(true);

    readInput(connection);
    return response;
}