Rectangle 27 25

while((inputLine = buff_read.readLine())!= null){
        System.out.println(inputLine);
    }
Document doc = builder.parse(instream);

The parsing will fail, because you have passed it an empty stream.

I removed the readLine() statement. But I am still getting the same error. If I supply the direct link to the xml it works. If I try to process using connection.getInputStream() if throws that error.

There was also an issue with stream that was being return. Problem solved.

@Fabii What was the issue with the stream being returned? I want to know because I'm getting the same issue.

You are right, you cannot read input stream twice. Nice explanation is also here: danielschneller.com/2008/01/

java - Why am I getting this error Premature end of file? - Stack Over...

java xml httpurlconnection
Rectangle 27 25

while((inputLine = buff_read.readLine())!= null){
        System.out.println(inputLine);
    }
Document doc = builder.parse(instream);

The parsing will fail, because you have passed it an empty stream.

I removed the readLine() statement. But I am still getting the same error. If I supply the direct link to the xml it works. If I try to process using connection.getInputStream() if throws that error.

There was also an issue with stream that was being return. Problem solved.

@Fabii What was the issue with the stream being returned? I want to know because I'm getting the same issue.

You are right, you cannot read input stream twice. Nice explanation is also here: danielschneller.com/2008/01/

java - Why am I getting this error Premature end of file? - Stack Over...

java xml httpurlconnection
Rectangle 27 3

Your code written in the question works well

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
saxParser.parse(uc.getInputStream(), handler);

I can't see any problem here. Maybe when you try it the first time the file was changing, and was not complete.

But now I can confirm you that it works. I try it.

java - "Premature end of file" while parsing xml from the net - Stack ...

java xml-parsing sax
Rectangle 27 2

This happens mainly because the InputStream the DOM parser is consuming is empty

So in what I ran across, there might be two situations:

  • The InputStream you passed into the parser has been used and thus emptied.
  • The File or whatever you created the InputStream from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream.

java - Why am I getting this error Premature end of file? - Stack Over...

java xml httpurlconnection
Rectangle 27 4

You probably have an invalid invisible char at the end of file. You can go to the end with the cursor and then delete all chars after the last bracket. It has helped for me.

The word "continue" is a keyword in Java, you cannot use it as variable name.

Is it possible my IDE is.. broken? Because now I'm getting a "not a statement" error when I try and make an integer. Ill try and edit the post to show you

java - Class, Interface, or enum expected error with exceedingly simpl...

java class enums compiler-errors
Rectangle 27 1

This happens mainly because the InputStream the DOM parser is consuming is empty

So in what I ran across, there might be two situations:

  • The InputStream you passed into the parser has been used and thus emptied.
  • The File or whatever you created the InputStream from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream.

java - Why am I getting this error Premature end of file? - Stack Over...

java xml httpurlconnection
Rectangle 27 1

You are getting the error because the SAXBuilder is not intelligent enough to deal with "blank states". So it looks for at least an <xml ..> declaration, and when that causes a no data response it creates the exception you see rather than report the empty state.

java - Why am I getting this error Premature end of file? - Stack Over...

java xml httpurlconnection
Rectangle 27 1

You are getting the error because the SAXBuilder is not intelligent enough to deal with "blank states". So it looks for at least an <xml ..> declaration, and when that causes a no data response it creates the exception you see rather than report the empty state.

java - Why am I getting this error Premature end of file? - Stack Over...

java xml httpurlconnection
Rectangle 27 1

Your code works for me, so I suspect your credentials object (which you didn't provide) is not valid. In special, make sure you use a KeyVaultConfiguration instance.

AzureKVCredentials
package com.example.cli;

import java.util.*;
import java.util.concurrent.*;

import com.microsoft.aad.adal4j.*;
import org.apache.http.*;
import org.apache.http.message.*;

import com.microsoft.azure.keyvault.*;
import com.microsoft.azure.keyvault.authentication.*;
import com.microsoft.windowsazure.*;
import com.microsoft.windowsazure.core.pipeline.filter.*;

public class AzureKVCredentials extends KeyVaultCredentials {

    public static Configuration createConfiguration() {
        return KeyVaultConfiguration.configure(null, new AzureKVCredentials()); 
    }

    @Override
    public Header doAuthenticate(ServiceRequestContext request, Map<String, String> challenge) {
        try {
            String authorization = challenge.get("authorization");
            String resource = challenge.get("resource");
            AuthenticationResult authResult = getAccessToken(authorization, resource);
            return new BasicHeader("Authorization", authResult.getAccessTokenType() + " " + authResult.getAccessToken());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {

        String clientId = "<app id of your Azure application>";
        String clientKey = "<application key>";

        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            AuthenticationContext context = new AuthenticationContext(authorization, false, service);
            Future<AuthenticationResult> future = null;
            ClientCredential credentials = new ClientCredential(clientId, clientKey);
            future = context.acquireToken(resource, credentials, null);
            result = future.get();
        } finally {
            service.shutdown();
        }
        if (result == null) {
            throw new RuntimeException("authentication result was null");
        }
        return result;
    }

}

This code is based on these sources from the azure-sdk-for-java.

java - KeyVault integration - [Fatal Error] :1:1: Premature end of fil...

java azure azure-java-sdk
Rectangle 27 3

If you want just to check the file name, you can do this:

But this method check only the file name, not the content. A more complete method include the magic number test.

public boolean checkJPEG(File file) throws IOException {
   String fileName = file.getName().toUpperCase();
   boolean extension = fileName.endsWith(".JPG") || fileName.endsWith(".JPEG");
   if (!extension) {
      return false;
   }
   FileInputStream in = null;
   try {
      in = new FileInputStream(file)
      byte[] magic = new byte[3];
      int count = in.read(magic);
      if (count < 3) return false;
      return magic[0] == 0xFF && magic[1] == 0xD8 && magic[2] == 0xFF;
   } finally {
      try {
         if (in != null) in.close();
      } catch (IOException ex) {}
   }
}

java - How to validate a file with valid extension? - Stack Overflow

java file
Rectangle 27 2

exists() returns true if the file path is a valid directory even if the file isn't there. You can get around this by using:

File f = new File(filePathString);

if f.isFile() {/*Do whatever*/}

But I want to open the file for writing. I guess I could check for existence and if it exists open it for writing, but the problem then is the file could be removed between those two checks.

How to only open an existing file in java - Stack Overflow

java file
Rectangle 27 1

You can use unparsed-text() function which can read external file in. Or if you know that the external file is a valid xml, you can use document() function as well. Both XSLT 2.0 functions however - i think.

hi, i get compilation errors of the stylesheet when using the unparsed-text() function... no matter if i'm at XSLT2.0 or 1.0

java - Insert external file content as HTML through XSLT - Stack Overf...

java html xml xslt
Rectangle 27 1

For using Azure KeyVault, you can try to use Azure REST APIs to manage and operate the Key Vault. Please refer to the Key Vault REST document https://msdn.microsoft.com/en-us/library/azure/dn903630.aspx.

There are two set of APIs for Key Vault management and Keys & Secrets operations that need different access tokens from different resource uri.

https://management.core.windows.net/
https://vault.azure.net

Here is a sample code as references.

package aad.keyvault;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.naming.ServiceUnavailableException;
import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.io.IOUtils;

import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;

public class RestAPISample {

    private static final String subscriptionId = "<subscription_id>";
    private static final String resourceGroupName = "<resource_group_name>";
    private static final String vaultName = "<vault_name>";
    private static final String apiVersion = "2015-06-01";
    private static final String getKeyVaultInfoUri = String.format(
            "https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.KeyVault/vaults/%s?api-version=%s",
            subscriptionId, resourceGroupName, vaultName, apiVersion);

    private static final String tenantId = "<tenant_id>";
    private static final String authority = String.format("https://login.windows.net/%s", tenantId);
    private static final String clientId = "<client_id>";
    private static final String clientSecret = "<client_secret_key>";
    private static final String keyName = "<keyvault_key>";
    private static final String getInfoFromAKeyUri = String.format("https://%s.vault.azure.net/keys/%s?api-version=%s",
            vaultName, keyName, apiVersion);

    public static String getAccessToken(String resource)
            throws MalformedURLException, InterruptedException, ExecutionException, ServiceUnavailableException {
        AuthenticationContext context = null;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext(authority, true, service);
            ClientCredential credential = new ClientCredential(clientId, clientSecret);
            Future<AuthenticationResult> future = context.acquireToken(resource, credential, null);
            result = future.get();
        } finally {
            service.shutdown();
        }
        String accessToken = null;
        if (result == null) {
            throw new ServiceUnavailableException("authentication result was null");
        } else {
            accessToken = result.getAccessToken();
            System.out.println("Access Token: " + accessToken);
        }
        return accessToken;
    }

    public static void getKeyVaultInfo() throws MalformedURLException, IOException, ServiceUnavailableException,
            InterruptedException, ExecutionException {
        System.out.println(getKeyVaultInfoUri);
        HttpsURLConnection conn = (HttpsURLConnection) new URL(getKeyVaultInfoUri).openConnection();
        conn.setRequestProperty("Authorization", "Bearer " + getAccessToken("https://management.core.windows.net/"));
        conn.addRequestProperty("Content-Type", "application/json");
        String resp = IOUtils.toString(conn.getInputStream());
        System.out.println(resp);
    }

    public static void getKeyInfo() throws MalformedURLException, IOException, ServiceUnavailableException, InterruptedException, ExecutionException {
        System.out.println(getInfoFromAKeyUri);
        HttpsURLConnection conn = (HttpsURLConnection) new URL(getInfoFromAKeyUri).openConnection();
        conn.setRequestProperty("Authorization", "Bearer " + getAccessToken("https://vault.azure.net"));
        conn.addRequestProperty("Content-Type", "application/json");
        String resp = IOUtils.toString(conn.getInputStream());
        System.out.println(resp);
    }

    public static void main(String[] args)
            throws InterruptedException, ExecutionException, ServiceUnavailableException, IOException {
        getKeyVaultInfo();
        getKeyInfo();
    }

}
set-policy
Get information about a key
azure keyvault set-policy --vault-name <vault-name> --spn <service-principal-no.> --perms-to-keys '["get"]'
get

java - KeyVault integration - [Fatal Error] :1:1: Premature end of fil...

java azure azure-java-sdk
Rectangle 27 1

The magic number solution is already implemented: see this topic for links to the Java Mime Magic Library.

Thanks a lot for your comment. Its help me alot.

java - How to validate a file with valid extension? - Stack Overflow

java file
Rectangle 27 1

You can not be sure of a files type, unless you completely parse the file and verify that it adheres completely to the format specification. Only then you can be sure.

Checking the magic number is a quick way of checking with a high probability to guess the type correctly. But obviously its not foolproof, its easy to make a file that starts with the bytes FF D8 FF, which would look like its a jpeg, but there is obviously no guarantee that its really a jpeg.

Or just rely on the file extension.

You just have to make a trade between reliability and simplicity. If you want simple, trust the file extension. If you want safety, verify the file contents.

Well, at least he knows that if the magic number is incorrect, it is not a JPEG. So accidental renamings can be handled very well. This doesn't protect against maliciously faked JPEGs, and all what you says applies.

java - How to validate a file with valid extension? - Stack Overflow

java file
Rectangle 27 1

exists() returns true if the file path is a valid directory even if the file isn't there. You can get around this by using:

File f = new File(filePathString);

if f.isFile() {/*Do whatever*/}

But I want to open the file for writing. I guess I could check for existence and if it exists open it for writing, but the problem then is the file could be removed between those two checks.

How to only open an existing file in java - Stack Overflow

java file
Rectangle 27 1

exists() returns true if the file path is a valid directory even if the file isn't there. You can get around this by using:

File f = new File(filePathString);

if f.isFile() {/*Do whatever*/}

But I want to open the file for writing. I guess I could check for existence and if it exists open it for writing, but the problem then is the file could be removed between those two checks.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to only open an existing file in java - Stack Overflow

java file
Rectangle 27 1

I had the same problem too when trying import my .xml file into my java tool. And I found a good solution for this: 1. Open the .xml file with Notepad++ then save the .xml file as .rtf file. Then open this file in WordPad application. 2. Save the .rtf file as .txt file, then open it with Notepad, and save it as .xml file again. When saving in Notepad, near the end of the pop-up window, make sure choosing the option "Encoding: UTF-8". It worked for mine, hope it's useful for yours too.

java - invalid byte 2 of 2-byte UTF-8 sequence - Stack Overflow

java xml encoding
Rectangle 27 2

Your problem translates to this: you have an XSM file that doesn't match the schema and you want to transform it to something that's valid.

With XSOM, you can read the structure in the XSD and perhaps analyze the XML but it still would need additional mapping from the invalid form to the valid form. The use of a stylesheet would be much easier, because you would walk through the XML, using XPath nodes to handle the elements in the proper order. With an XML where you want apples before pears, the stylesheet would first copy the apple node (/Fruit/Apple) before it copies the pear node. That way, no matter of the order in the old file, they would be in the correct order in the new file.

What you could do with XSOM is to read the XSD and generate the stylesheet that will re-order the data. Then transform the XML using that stylesheet. once XSOM has generated a stylesheet for the XSD, you can just re-use the stylesheet until the XSD is modified or another XSD is needed.

Of course, you could use XSOM to copy nodes immediately in the right order. But since this means your code has to walk itself through all nodes and child nodes, it might take some time to process to finish. A stylesheet would do the same, but the transformer will be able to process it all faster. It can work directly on the data while the Java code would have to get/set every node through the XMLDocument properties.

When I think about this, I wonder if this has been done before already. It would be very generic and would be able to handle almost every XSD/XML.

Let's see... Using "//xsd:element/@name" you would get all element names in the schema. Every unique name would need to be translated to a template. Within these templates, you would need to process the child nodes of the specific element, which is slightly more complex to get. Elements can have a reference, which you would need to follow. Otherwise, get all child xsd:element nodes it.

OK, cool, we're both on the same page now :) I agree that a XSL transform would re-arrange my document more efficiently than manually poking around in the DOM, but the initial problem of using the XSOM API to find out what the order should be remains, regardless of the mechanism I use to perform the re-ordering itself.

I suddenly wonder if it isn't possible to use a stylesheet to transform an XSD into an XML-copying stylesheet. Would make an interesting cross-platform solution. If you're already familiar with XSD's and XSLT's then this might be easier than having to learn more about XSOM.

I dunno, schemas can be fearsomely complex, especially the ones I'm working with.... extended types, substitution groups, all that stuff. Scary.

java - Using a schema to reorder the elements of an XML document in co...

java xml xsd xsom
Rectangle 27 7

/**
 * Check if the image is a PNG. The first eight bytes of a PNG file always
 * contain the following (decimal) values: 137 80 78 71 13 10 26 10 / Hex:
 * 89 50 4e 47 0d 0a 1a 0a
 */
public boolean isValidPNG(InputStream is) {
    try {
        byte[] b = new byte[8];
        is.read(b, 0, 8);
        if (Arrays.equals(b, new BigInteger("89504e470d0a1a0a",16).toByteArray())) {
            return true;
        }
    } catch (Exception e) {
        //Ignore
        return false;
    }
    return false;
}

/**
 * Check if the image is a JPEG. JPEG image files begin with FF D8 and end
 * with FF D9
 */
public boolean isValidJPEG(InputStream is, int size) {
    try {
        byte[] b = new byte[2];
        is.read(b, 0, 2);
        // check first 2 bytes:
        if ((b[0]&0xff) != 0xff || (b[1]&0xff) != 0xd8) {
            return false;
        }
        // check last 2 bytes:
        is.skip(size-4);
        is.read(b, 0, 2);
        if ((b[0]&0xff) != 0xff || (b[1]&0xff) != 0xd9) {
            return false;
        }
    } catch (Exception e) {
        // Ignore
        return false;
    }
    return true;
}

/** Check if the image is a valid GIF. GIF files start with GIF and 87a or 89a.
 * http://www.onicos.com/staff/iz/formats/gif.html
*/
public boolean isValidGIF(InputStream is) {
    try {
        byte[] b=new byte[6];
        is.read(b, 0, 6);
        //check 1st 3 bytes
        if(b[0]!='G' || b[1]!='I' || b[2]!='F') {
            return false;
        }
        if(b[3]!='8' || !(b[4]=='7' || b[4]=='9') || b[5]!='a') {
            return false;
        }
    } catch(Exception e) {
        // Ignore
        return false;
    }
    return true;
}

Your method isValidPNG helped me, but I had to change something. Somehow the byte array you create from that BigInteger contains 9 bytes, not 8, from which the first is of value zero. I had to chop it off (by wrapping the "wrong" byte array in Arrays.copyOfRange(byteArray, 1, 9).

How to validate image header in java - Stack Overflow

java image file mime-types magic-numbers