/*
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2016, Gluu
 */
package org.gluu.saml.metadata;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;
import java.net.URL;
import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.io.IOUtils;
import org.gluu.service.document.store.service.DocumentStoreService;
import org.gluu.util.io.HTTPFileDownloader;
import org.slf4j.Logger;
import org.xml.sax.SAXException;

/**
 * SAML metadata parser.
 *
 * @author Dmitry Ognyannikov
 */

@ApplicationScoped
public class SAMLMetadataParser {

	@Inject
	private Logger log;

	@Inject
	private DocumentStoreService documentStoreService;

    public List<String> getEntityIdFromMetadataFile(String metadataFile) {
        if (!documentStoreService.hasDocument(metadataFile)) {
            return null;
        }

        EntityIDHandler handler = parseMetadata(metadataFile);
        if(handler!=null){
            List<String> entityIds = handler.getEntityIDs();
            if (entityIds == null || entityIds.isEmpty()) {
                log.error("Failed to find entityId in metadata file: " + metadataFile);
            }
            return entityIds;
        }else{
           return null;
        }
    }

    public List<String> getSpEntityIdFromMetadataFile(String metadataFile) {
        EntityIDHandler handler = parseMetadata(metadataFile);
        if(handler!=null){
            List<String> entityIds = handler.getSpEntityIDs();

            if (entityIds == null || entityIds.isEmpty()) {
            	log.error("Failed to find entityId in metadata file: " + metadataFile);
            }

            return entityIds;
        }else {
            return null;
        }

    }

    public EntityIDHandler parseMetadata(String metadataFile) {
        if (!documentStoreService.hasDocument(metadataFile)) {
            log.error("Failed to get entityId from metadata file: " + metadataFile);
            return null;
        }

        InputStream is = null;
        try {
            is = documentStoreService.readDocumentAsStream(metadataFile);

            return parseMetadata(is);
        } catch (Exception ex) {
            log.error("Failed to read SAML metadata file: " + metadataFile, ex);
            return null;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public EntityIDHandler parseMetadata(InputStream is) {
        InputStreamReader isr = null;
        EntityIDHandler handler = null;
        try {
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = saxParserFactory.newSAXParser();
            handler = new EntityIDHandler();
            saxParser.parse(is, handler);
        } catch (IOException ex) {
            log.error("Failed to read SAML metadata", ex);
        } catch (ParserConfigurationException e) {
            log.error("Failed to confugure SAX parser", e);
        } catch (SAXException e) {
            log.error("Failed to parse SAML metadata", e);
        } finally {
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(is);
        }


        return handler;
    }

    public EntityIDHandler parseMetadata(URL metadataURL) {
        String metadataFileContent = HTTPFileDownloader.getResource(metadataURL.toExternalForm(), "application/xml, text/xml", null, null);

        if (metadataFileContent == null) {
            return null;
        }

        InputStream is = new StringBufferInputStream(metadataFileContent);

        return parseMetadata(is);
    }

}


@@ -171,16 +171,37 @@
 adata;%0A%0A
+import java.io.File;%0A
 import j
@@ -212,32 +212,32 @@
 io.IOException;%0A
-
 import java.io.I
@@ -581,16 +581,56 @@
 ctory;%0A%0A
+import org.apache.commons.io.FileUtils;%0A
 import o
@@ -1608,32 +1608,503 @@
 %0A        %7D%0A    %7D
+%0A    %0A    public List%3CString%3E getEntityIdFromMetadataFile(File metadataFile) %7B%0A        if (!metadataFile.isFile()) %7B%0A            return null;%0A        %7D%0A        EntityIDHandler handler = parseMetadata(metadataFile);%0A%0A        List%3CString%3E entityIds = handler.getEntityIDs();%0A%0A        if (entityIds == null %7C%7C entityIds.isEmpty()) %7B%0A        %09log.error(%22Failed to find entityId in metadata file: %22 + metadataFile.getAbsolutePath());%0A        %7D%0A%0A        return entityIds;%0A    %7D
 %0A%0A    public Lis
@@ -3000,32 +3000,32 @@
 Exception ex) %7B%0A
-
             log.
@@ -3183,24 +3183,651 @@
      %7D%0A    %7D
+%0A    %0A    public EntityIDHandler parseMetadata(File metadataFile) %7B%0A        if (!metadataFile.exists()) %7B%0A            log.error(%22Failed to get entityId from metadata file: %22 + metadataFile.getAbsolutePath());%0A            return null;%0A        %7D%0A%0A        InputStream is = null;%0A        try %7B%0A            is = FileUtils.openInputStream(metadataFile);%0A        %0A            return parseMetadata(is);%0A        %7D catch (IOException ex) %7B%0A            log.error(%22Failed to read SAML metadata file: %22 + metadataFile.getAbsolutePath(), ex);%0A            return null;%0A        %7D finally %7B%0A            IOUtils.closeQuietly(is);%0A        %7D%0A    %7D
 %0A%0A    public

add method for saml api