package edu.harvard.iq.dataverse.api;

import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DatasetServiceBean;
import edu.harvard.iq.dataverse.Dataverse;
import edu.harvard.iq.dataverse.DataverseServiceBean;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("browse")
public class Browse {

    private static final Logger logger = Logger.getLogger(Browse.class.getCanonicalName());

    @EJB
    DataverseServiceBean dataverseService;
    @EJB
    DatasetServiceBean datasetService;

    @GET
    public String browse() throws FileNotFoundException {
        try {
            logger.info("indexing...");
            if (dataverseService == null) {
                return "dataverseService is null\n";
            }
            List<Dataverse> dataverses = dataverseService.findAll();
            JsonArrayBuilder filesArrayBuilder = Json.createArrayBuilder();
            JsonArrayBuilder dataversesArrayBuilder = Json.createArrayBuilder();
            JsonArrayBuilder datasetsArrayBuilder = Json.createArrayBuilder();
            for (Dataverse dataverse : dataverses) {
                logger.info("dataverse: " + dataverse.getAlias());
                JsonObjectBuilder dataverseInfoBuilder = Json.createObjectBuilder().add("alias", dataverse.getAlias());
                dataversesArrayBuilder.add(dataverseInfoBuilder);
                Long ownerId = dataverse.getId();
                List<Dataset> datasets = datasetService.findByOwnerId(ownerId);
                for (Dataset dataset : datasets) {
                    logger.info("dataset: " + dataset.getTitle());
                    String datasetInfo = dataverse.getAlias() + "|" + dataset.getTitle();
                    JsonObjectBuilder datasetObjectBuilder = Json.createObjectBuilder().add("datasetInfo", datasetInfo);
                    datasetsArrayBuilder.add(datasetObjectBuilder);
                    List<DataFile> files = dataset.getFiles();
                    for (DataFile file : files) {
                        logger.info("file: " + file.getName());
                        String fileInfo = dataverse.getAlias() + "|" + dataset.getTitle() + "|" + file.getName();
                        JsonObjectBuilder fileInfoBuilder = Json.createObjectBuilder().add("fileInfo", fileInfo);
                        filesArrayBuilder.add(fileInfoBuilder);
                    }
                }
            }
            JsonObject jsonObject = Json.createObjectBuilder()
                    .add("dataverses_total_count", dataversesArrayBuilder.build().size())
                    .add("dataverses", dataversesArrayBuilder)
                    .add("datasets_total_count", datasetsArrayBuilder.build().size())
                    .add("datasets", datasetsArrayBuilder)
                    .add("files_total_count", filesArrayBuilder.build().size())
                    .add("files", filesArrayBuilder)
                    .build();
            return Util.jsonObject2prettyString(jsonObject);
        } catch (NullPointerException ex) {
            StackTraceElement stacktrace = ex.getStackTrace()[0];
            if (stacktrace != null) {
                String javaFile = stacktrace.getFileName();
                String methodName = stacktrace.getMethodName();
                int lineNumber = stacktrace.getLineNumber();
                String error = "Indexing failed. " + ex.getClass().getCanonicalName() + " on line " + javaFile + ":" + lineNumber + " (method: " + methodName + ")";
                logger.info(error);
                /**
                 * @todo use Util.message2ApiError() instead
                 */

                JsonObject jsonObject = Json.createObjectBuilder()
                        .add("message", "Error")
                        .add("documentation_url", "http://thedata.org")
                        .add("errors", Json.createArrayBuilder()
                                .add(Json.createObjectBuilder()
                                        .add("code", error)))
                        .build();
                logger.info("jsonObject: " + jsonObject);
                return Util.jsonObject2prettyString(jsonObject);
            } else {
                return null;
            }
        }
    }

}

@@ -380,16 +380,47 @@
 jb.EJB;%0A
+import javax.ejb.EJBException;%0A
 import j
@@ -530,32 +530,131 @@
 nObjectBuilder;%0A
+import javax.validation.ConstraintViolation;%0Aimport javax.validation.ConstraintViolationException;%0A
 import javax.ws.
@@ -1005,159 +1005,8 @@
 y %7B%0A
-            logger.info(%22indexing...%22);%0A            if (dataverseService == null) %7B%0A                return %22dataverseService is null%5Cn%22;%0A            %7D%0A
     
@@ -3268,19 +3268,865 @@
 ch (
-NullPointer
+EJBException ex) %7B%0A            Throwable cause = ex;%0A            StringBuilder sb = new StringBuilder();%0A            while (cause.getCause() != null) %7B%0A                cause = cause.getCause();%0A                sb.append(cause.getClass().getCanonicalName() + %22 %22);%0A                if (cause instanceof ConstraintViolationException) %7B%0A                    ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;%0A                    for (ConstraintViolation%3C?%3E violation : constraintViolationException.getConstraintViolations()) %7B%0A                        sb.append(violation.toString() + %22 %22);%0A                        sb.append(%22(invalid value: %3C%3C%3C%22 + violation.getInvalidValue() + %22%3E%3E%3E)%22);%0A                    %7D%0A                %7D%0A            %7D%0A            return Util.message2ApiError(sb.toString());%0A        %7D catch (
 Exce
@@ -4462,13 +4462,13 @@
  = %22
-Index
+Brows
 ing 

print bean validation constraint violations