-2

I'm trying to access some URL via Java.

In my code I have provided credentials for the server authentication. I have also extracted a list (in xml form) of available URL's on the server and put them into an array where I can call each of the URL in the list automatically.

This is my code:

import java.io.File;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.lang.reflect.Array;
import org.apache.http.HttpEntity;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

public class ClientAuthentication {

public static void main(String[] args) throws Exception {
    /*CREATING FILE*/
    File myFile = new File("C:/input.xml");

    /*DEFINING CREDENTIALS*/
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 80),new UsernamePasswordCredentials(" ", " "));

    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()){
        HttpGet httpget = new HttpGet("http://localhost/app/rest/buildTypes");
        /*WRITE TO FILE*/
        try (CloseableHttpResponse response = httpclient.execute(new HttpGet("http://localhost/app/rest/buildTypes"))){
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                try (FileOutputStream outstream = new FileOutputStream(myFile)) {
                entity.writeTo(outstream);
                }
            }
        }

        /*SHOW EXECUTION*/
        System.out.println("Executing request " + httpget.getRequestLine());
        try (CloseableHttpResponse response = httpclient.execute(httpget)) {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        }
    }

    /*Extract all Build ID from XML file*/
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("C:/input.xml");
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("//buildTypes/buildType[@id]");
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

    /*Creating url and saving into array*/
    String array[] = new String[100];
    for (int i = 0; i < nl.getLength(); i++){
        Node currentItem = nl.item(i);
        String key = currentItem.getAttributes().getNamedItem("id").getNodeValue();
        String pathing = "http://localhost/app/rest/" + (key);
        System.out.println(pathing);
        array[i] = pathing;
    }

    /*Getting the url*/
    int size = Array.getLength(array);
    for (int i = 0; i < size; i++){
        try (CloseableHttpClient areq = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()){
                HttpGet httpget = new HttpGet(array[i]);

                /*SHOW EXECUTION*/
                System.out.println("Executing request " + httpget.getRequestLine());
                try (CloseableHttpResponse response = areq.execute(httpget)) {
                    System.out.println("----------------------------------------");
                    System.out.println(response.getStatusLine());
                    System.out.println(EntityUtils.toString(response.getEntity()));
                }
            }
    }
}  
}

The output error is:

Exception in thread "main" java.lang.NullPointerException
    at java.net.URI$Parser.parse(URI.java:3042)
    at java.net.URI.<init>(URI.java:588)
    at java.net.URI.create(URI.java:850)
    at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:66)
    at ClientAuthentication.main(ClientAuthentication.java:85)
Java returned: 1 BUILD FAILED (total time: 0 seconds)

I think the problem is at the last parts of the code (getting the URL). I don't know what the problem is though. Can anyone please help?

jrtapsell
  • 6,719
  • 1
  • 26
  • 49

1 Answers1

0
String array[] = new String[100];
for (int i = 0; i < nl.getLength(); i++){
    ...

Why are you using 100 instead of nl.getLength ?

Since you iterate this array later to instanciate the HttpGet, every last cells not instanciate are still null, leading to new HttpGet(array[i]) throwing an exception beause the parameter can't be null.

int size = Array.getLength(array);
for (int i = 0; i < size; i++){
    try (CloseableHttpClient areq = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()){
            HttpGet httpget = new HttpGet(array[i]); 

This will works until you reach the null remaining in your array.

Instanciate your array with new String[nl.getLength()]. Since you now you don't need more. (or less).

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • You're a genius! Thank you this fixed the problem! – SandraNotFound Oct 19 '17 at 10:59
  • 1
    You are welcome @CassandraLehmann. You should learn to use a debugger. This issues is not complicate to localize, so you could have fixed this yourself in a short amount of time. – AxelH Oct 19 '17 at 11:01
  • I just stated coding and didn't know there was a debugger. But I will definitely look into it now. Thanks again! – SandraNotFound Oct 19 '17 at 11:05