Example usage for java.io FileNotFoundException getMessage

List of usage examples for java.io FileNotFoundException getMessage

Introduction

In this page you can find the example usage for java.io FileNotFoundException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.dareu.web.core.service.impl.AccountServiceImpl.java

@Override
public Response getAccountImage(String userId) throws InvalidRequestException, InternalApplicationException {
    if (userId == null || userId.isEmpty()) {
        throw new InvalidRequestException("No user id provided");
    }/*ww  w  .j  a v a 2 s  .co  m*/
    //get file 
    InputStream stream = null;
    try {
        stream = fileService.getFile(userId + ".jpg", FileType.PROFILE_IMAGE);
        BufferedImage image = ImageIO.read(stream);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        ImageIO.write(image, "jpg", out);

        return Response.ok(out.toByteArray()).build();
    } catch (FileNotFoundException ex) {
        throw new InvalidRequestException("The provided id is not valid");
    } catch (IOException ex) {
        throw new InternalApplicationException("Could not get account profile image: " + ex.getMessage());
    }
}

From source file:com.ExtendedAlpha.SWI.Data.DataSeparator.java

public void getPlayerDataFromFile(Player player, String group, String gamemode) {
    File file;//ww  w  . java 2  s. co  m
    if (gamemode.equalsIgnoreCase("SURVIVAL")) {
        file = new File(FILE_PATH + player.getUniqueId().toString(), group + ".json");
    } else if (gamemode.equalsIgnoreCase("ADVENTURE")) {
        file = new File(FILE_PATH + player.getUniqueId().toString(), group + "_adventure.json");
    } else {
        file = new File(FILE_PATH + player.getUniqueId().toString(), group + "_creative.json");
    }

    try {
        JSONObject data = Separator.getObjectFromFile(file);
        PlayerSeparator.setPlayer(data, player);
    } catch (FileNotFoundException ex) {
        try {
            file.createNewFile();
            JSONObject defaultGroupData = Separator
                    .getObjectFromFile(new File(FILE_PATH + "settings" + File.separator + group + ".json"));
            PlayerSeparator.setPlayer(defaultGroupData, player);
        } catch (FileNotFoundException ex2) {
            try {
                JSONObject defaultData = Separator
                        .getObjectFromFile(new File(FILE_PATH + "settings" + File.separator + "settings.json"));
                PlayerSeparator.setPlayer(defaultData, player);
            } catch (FileNotFoundException ex3) {
                plugin.getPrinter().printToPlayer(player,
                        "Something went horribly wrong when loading your inventory! "
                                + "Please notify a server administrator!",
                        true);
                plugin.getPrinter().printToConsole("Unable to find inventory data for player '"
                        + player.getName() + "' for group '" + group + "': " + ex3.getMessage(), true);
            }
        } catch (IOException exIO) {
            Messages.getInstance(plugin).printToConsole("Error creating file '" + FILE_PATH
                    + player.getUniqueId().toString() + File.separator + group + ".json': " + ex.getMessage(),
                    true);
        }
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private void writeSignature(String tokenString, byte[] signature) {

    String signatureDir = ConfigurationListener.getSignatureDir();
    String signatureFile = signatureDir + tokenString;

    FileOutputStream sigFOS = null;

    try {//from   w  ww  .  j a v  a2  s . co m
        sigFOS = new java.io.FileOutputStream(signatureFile);
        sigFOS.write(signature);
        sigFOS.close();
    } catch (FileNotFoundException e) {
        logger.error("Gatekeeper.writeSignature: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error("Gatekeeper.writeSignature: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:com.aurel.track.exchange.excel.ExcelImportAction.java

/**
 * Execute the import from excel/*  w w  w .ja  v a2  s .c o m*/
 * @return
 */
public String excelImport() {
    String excelMappingsDirectory = AttachBL.getExcelImportDirBase() + personID;
    Workbook workbook = ExcelFieldMatchBL.loadWorkbook(excelMappingsDirectory, fileName);
    Set<Integer> lastSavedIdentifierFieldIDIsSet = null;
    Map<String, Integer> columNameToFieldIDMap = null;
    try {
        File file = new File(excelMappingsDirectory, mappingFileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        columNameToFieldIDMap = (Map<String, Integer>) objectInputStream.readObject();
        lastSavedIdentifierFieldIDIsSet = (Set<Integer>) objectInputStream.readObject();
        objectInputStream.close();
    } catch (FileNotFoundException e) {
        LOGGER.warn("Creating the input stream for mapping failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.warn("Saving the mapping failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (ClassNotFoundException e) {
        LOGGER.warn("Class not found for  the mapping " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }

    if (workbook == null) {
        JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageJSON(
                ImportJSON.ERROR_CODES.ERROR_MESSAGE, getText("admin.actions.importTp.err.uploadAgain"), true));
        return null;
    }
    if (columNameToFieldIDMap == null) {
        //for example the sheet contains no columns at all
        columNameToFieldIDMap = new HashMap<String, Integer>();
    }
    try {
        Map<Integer, String> columnIndexToColumNameMap = ExcelFieldMatchBL.getFirstRowHeaders(workbook,
                selectedSheet);
        Map<Integer, Integer> columnIndexToFieldIDMap = ExcelImportBL
                .getColumnIndexToFieldID(columNameToFieldIDMap, columnIndexToColumNameMap);
        Map<Integer, Integer> fieldIDToColumnIndexMap = ExcelImportBL.reverseMap(columnIndexToFieldIDMap);
        List<ErrorData> errorDataList = ExcelImportBL.validateRequiredColumns(workbook, selectedSheet,
                fieldIDToColumnIndexMap, lastSavedIdentifierFieldIDIsSet, invalidValueHandlingMap,
                defaultValuesMap, locale);
        if (!errorDataList.isEmpty()) {
            //required columns are missing: do not disable the Finish button and do not delete
            //the file because it may be solved by stepping back and forth in the wizard
            JSONUtility.encodeJSON(servletResponse,
                    ImportJSON.importErrorMessageListJSON(
                            ErrorHandlerJSONAdapter.handleErrorList(errorDataList, locale),
                            ImportJSON.ERROR_CODES.ERROR_MESSAGES, false));
            return null;
        } else {
            //delete the file for this case because it
            //either results in a error which should be resolved in the excel file
            //consequently a new upload cannot be avoided before re-import
            //or everything is fine and in this case no new import is needed
            //with any other return a
            //grid errors
            Map<Integer, SortedMap<Integer, SortedMap<String, ErrorData>>> gridErrorsMap = new HashMap<Integer, SortedMap<Integer, SortedMap<String, ErrorData>>>();
            //row errors
            Map<Integer, SortedSet<Integer>> rowErrorsMap = new HashMap<Integer, SortedSet<Integer>>();
            Map<Integer, SortedSet<Integer>> requiredFieldErrorsMap = new HashMap<Integer, SortedSet<Integer>>();
            Map<Integer, Map<Integer, List<Integer>>> rowNoToPseudoFieldsOriginal = new HashMap<Integer, Map<Integer, List<Integer>>>();
            Map<Integer, Map<Integer, List<Integer>>> rowNoToPseudoFieldsExcel = new HashMap<Integer, Map<Integer, List<Integer>>>();
            Map<Integer, Integer> rowToParentRow = new HashMap<Integer, Integer>();
            SortedMap<Integer, TWorkItemBean> workItemBeansMap = ExcelImportBL.getAndValidateGridData(workbook,
                    selectedSheet, personID, locale, columnIndexToFieldIDMap, fieldIDToColumnIndexMap,
                    lastSavedIdentifierFieldIDIsSet, defaultValuesMap, invalidValueHandlingMap,
                    rowNoToPseudoFieldsOriginal, rowNoToPseudoFieldsExcel, gridErrorsMap, rowErrorsMap,
                    requiredFieldErrorsMap, rowToParentRow);
            Collection<TWorkItemBean> workItemBeans = workItemBeansMap.values();
            if (gridErrorsMap.isEmpty() && rowErrorsMap.isEmpty() && requiredFieldErrorsMap.isEmpty()) {
                List<Integer> alreadyExistingRows = ExcelImportBL.getExistingWorkItemRows(workItemBeans);
                //already existing rows with the same synopsis, project, issueType and release scheduled
                //(independently of the identifierFieldIDs) to avoid importing the same new issues more
                //(only the not found i.e. new issues are tested)
                if (!alreadyExistingRows.isEmpty()) {
                    JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageJSON(
                            ImportJSON.ERROR_CODES.ERROR_MESSAGE,
                            LocalizeUtil.getParametrizedString("admin.actions.importExcel.err.existingRows",
                                    new String[] { MergeUtil.getMergedString(alreadyExistingRows, ", ") },
                                    locale),
                            true));
                    return null;
                } else {
                    Set<Integer> presentFieldIDs = ExcelImportBL.getPresentFields(columNameToFieldIDMap);
                    presentFieldIDs.addAll(FieldsManagerRT.getRequiredSystemFieldsList());
                    //the explicit change of this field is not allowed
                    presentFieldIDs.remove(SystemFields.LASTMODIFIEDDATE);
                    presentFieldIDs.remove(SystemFields.CREATEDATE);
                    Map<Integer, Map<Integer, Map<Integer, TFieldConfigBean>>> projectsIssueTypesFieldConfigsMap = FieldRuntimeBL
                            .getFieldConfigsForWorkItemBeans(workItemBeans, presentFieldIDs, locale);
                    Map<Integer, Map<Integer, Map<String, Object>>> projectsIssueTypesFieldSettingsMap = FieldRuntimeBL
                            .getFieldSettingsForFieldConfigs(projectsIssueTypesFieldConfigsMap);
                    Map<Integer, WorkItemContext> existingIssueContextsMap = FieldsManagerRT
                            .createImportContext(workItemBeans, presentFieldIDs,
                                    projectsIssueTypesFieldConfigsMap, projectsIssueTypesFieldSettingsMap, null,
                                    null, personID, locale);
                    SortedMap<Integer, List<ErrorData>> validationErrorsMap = FieldsManagerRT.validateWorkItems(
                            workItemBeans, presentFieldIDs, existingIssueContextsMap,
                            projectsIssueTypesFieldConfigsMap, projectsIssueTypesFieldSettingsMap, personID,
                            locale);
                    //validation errors: either grid (workItem and field) or row (workItem) level errors. There is a chance to resolve the problems
                    //without modifying the excel file: for ex. by setting further/other default values
                    if (!validationErrorsMap.isEmpty()) {
                        List<String> rowErrors = ExcelImportBL.renderRowErrors(validationErrorsMap,
                                fieldIDToColumnIndexMap, locale);
                        JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON(rowErrors,
                                ImportJSON.ERROR_CODES.ERROR_MESSAGES, false));
                        return null;
                    } else {
                        if (overwriteMap == null) {
                            overwriteMap = new HashMap<String, Boolean>();
                        }
                        SortedMap<Integer, SortedMap<Integer, Map<Integer, Object>>> confictsMap = ExcelImportBL
                                .conflictResolutionWorkItems(workItemBeans, presentFieldIDs,
                                        existingIssueContextsMap, projectsIssueTypesFieldConfigsMap,
                                        columnIndexToColumNameMap, fieldIDToColumnIndexMap, personID, locale,
                                        overwriteMap);
                        if (confictsMap != null && !confictsMap.isEmpty()) {
                            //render conflicts
                            //do not disable Finish and do not delete the file instead resolve the conflicts and import again
                            JSONUtility.encodeJSON(servletResponse,
                                    ExcelImportJSON.getExcelConflictsJSON(confictsMap, locale, false));
                            return null;
                        } else {
                            //no conflicts or conflict handling is set (overwriteMap was submitted)
                            List<ErrorData> errorsList = new ArrayList<ErrorData>();
                            ImportCounts importCounts = FieldsManagerRT.saveWorkItems(workItemBeansMap,
                                    presentFieldIDs, existingIssueContextsMap,
                                    projectsIssueTypesFieldConfigsMap, projectsIssueTypesFieldSettingsMap,
                                    rowNoToPseudoFieldsOriginal, rowNoToPseudoFieldsExcel, rowToParentRow,
                                    personID, locale, errorsList);
                            if (!errorsList.isEmpty()) {
                                JSONUtility.encodeJSON(servletResponse,
                                        ImportJSON.importErrorMessageListJSON(
                                                ErrorHandlerJSONAdapter.handleErrorList(errorDataList, locale),
                                                ImportJSON.ERROR_CODES.ERROR_MESSAGES, true));
                                return null;
                            }
                            JSONUtility.encodeJSON(servletResponse,
                                    ImportJSON.importMessageJSON(true,
                                            LocalizeUtil.getParametrizedString(
                                                    "admin.actions.importExcel.message.importResult",
                                                    new String[] {
                                                            Integer.valueOf(importCounts.getNoOfCreatedIssues())
                                                                    .toString(),
                                                            Integer.valueOf(importCounts.getNoOfUpdatedIssues())
                                                                    .toString() },
                                                    locale),
                                            true, locale));
                            //successful import, delete the file
                            File file = new File(excelMappingsDirectory, fileName);
                            file.delete();
                            return null;
                        }
                    }
                }
            } else {
                //grid or row errors
                Map<Integer, List<String>> gridErrorsForJsonMap = null;
                if (!gridErrorsMap.isEmpty()) {
                    gridErrorsForJsonMap = ExcelImportBL.getGridErrorsForJsonMap(gridErrorsMap, locale);
                }
                Map<String, String> rowErrorsForJsonMap = null;
                if (!rowErrorsMap.isEmpty()) {
                    rowErrorsForJsonMap = ExcelImportBL.getRowErrorsForJsonMap(rowErrorsMap);
                }
                List<String> requiredFieldErrorsList = null;
                if (!requiredFieldErrorsMap.isEmpty()) {
                    requiredFieldErrorsList = ExcelImportBL
                            .getMissingRequiredFieldErrorsForJsonMap(requiredFieldErrorsMap, locale);
                }
                JSONUtility.encodeJSON(servletResponse, ExcelImportJSON.getExcelWrongGridValuesJSON(
                        gridErrorsForJsonMap, rowErrorsForJsonMap, requiredFieldErrorsList, locale, true));
            }
        }
    } catch (Exception e) {
        addActionError(getText("admin.actions.importTp.err.failed"));
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        JSONUtility.encodeJSON(servletResponse,
                ImportJSON.importErrorMessageJSON(ImportJSON.ERROR_CODES.ERROR_MESSAGE, LocalizeUtil
                        .getLocalizedTextFromApplicationResources("admin.actions.importTp.err.failed", locale),
                        true));
    }
    //delete the uploaded excel file
    return null;
}

From source file:domain.Proceso.java

public void cargarArchivoSql(String archivoSQL) {

    String linea;/*from w w  w .  java 2 s  .  c o  m*/

    log.log("cargando Archivo " + archivoSQL, false);

    try {

        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;

        archivo = new File(archivoSQL);
        fr = new FileReader(archivo);
        br = new BufferedReader(fr);

        // Lectura del fichero                    
        while ((linea = br.readLine()) != null) {

            //  System.out.println(linea);
            if (linea.contains("[") && linea.contains("]")) {

                encabezado = linea.substring(1, linea.length() - 1);
                //  System.out.println(encabezado);
            } else {
                Tables tables = Tables.valueOf(encabezado);

                switch (tables) {

                case rancho:
                    rancho.actualizar(linea);
                    break;

                case concepto_movimiento:
                    concepto_movimiento.actualizar(linea);
                    break;

                case corral:
                    corral.actualizar(linea);
                    break;

                case corral_animal:
                    corral_animal.actualizar(linea);
                    break;

                case animal:
                    animal.actualizar(linea);
                    break;

                case movimiento:
                    movimiento.actualizar(linea);
                    break;

                case detalle_movimiento:
                    detalle_movimiento.actualizar(linea);
                    break;

                case medicina:
                    medicina.actualizar(linea);
                    break;

                case medicina_animal:
                    medicina_animal.actualizar(linea);
                    break;

                case corral_datos:
                    corral_datos.actualizar(linea);
                    break;

                case cria:
                    cria.actualizar(linea);
                    break;

                case proveedor:
                    proveedor.actualizar(linea);
                    break;

                case raza:
                    raza.actualizar(linea);
                    break;

                case tratamiento:
                    tratamiento.actualizar(linea);
                    break;

                case medicina_tratamiento:
                    medicina_tratamiento.actualizar(linea);
                    break;
                }
            }
        }

        //cierra el archivo para poder borrarlo despues
        br.close();
    } catch (FileNotFoundException ex) {

        log.log("Error: " + ex.getMessage(), true);
        Logger.getLogger(Proceso.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {

        log.log("Error: " + ex.getMessage(), true);
        Logger.getLogger(Proceso.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.du.penrose.systems.fedoraApp.ProgramFileProperties.java

/**
 * Load the properties file, if the file has not yet been loaded or if the
 * file has been updated on the file system. If the file does not exist 
 * create it.<br><br>//  w  ww .  j a  v  a 2  s.com
 * NOTE: This is the only method that should be accessing this.myProperties
 * variable directly!
 * 
 * @return File which is the Properties file managed by this obj.
 */
protected File checkAndLoadPropertiesFile() {

    File inFile = null;
    if (this.myProperties == null) {
        this.myProperties = new Properties();
    }

    try {
        inFile = this.getPropertiesFile();
        // this.logger.info( "looking for properties file: " + inFile.getAbsolutePath() );
        if (!inFile.exists()) {
            inFile.createNewFile();
            this.logger.info("Not found, creating properties file: " + inFile.getAbsolutePath());
        }
        if (this.lastFileUpdate != inFile.lastModified()) {
            // this.logger.info( "Reloading properties file: " + inFile.getAbsolutePath() );
            this.myProperties = new Properties(); //needed to ensure update when a property is commented out.
            this.myProperties.load(new FileInputStream(inFile));
            this.lastFileUpdate = inFile.lastModified();
        }
    } catch (FileNotFoundException e) {
        myProperties = null;
        this.logger.error("Properties File NOT found: " + inFile.getAbsoluteFile());
    } catch (IOException e) {
        this.logger.error("Properties File IO Exception: " + inFile.getAbsoluteFile());
        myProperties = null;
        String errorMsg = "IO Exception: " + e.getMessage();
        this.logger.error(errorMsg);
        throw new RuntimeException(errorMsg);
    }

    return inFile;

}

From source file:mekhq.Utilities.java

public static void copyfile(File inFile, File outFile) {
    try {//from w  w  w  .j av  a2 s. c o  m
        InputStream in = new FileInputStream(inFile);

        //For Append the file.
        //  OutputStream out = new FileOutputStream(f2,true);

        //For Overwrite the file.
        OutputStream out = new FileOutputStream(outFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied."); //$NON-NLS-1$
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage() + " in the specified directory."); //$NON-NLS-1$
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Boolean isValidSignature(String tokenString, byte[] signature) {

    Boolean isValid = false;//from w  w w.  j a va 2 s  .  c  o  m

    File lterCert = ConfigurationListener.getLterCertificate();

    try {

        FileInputStream certFis = new FileInputStream(lterCert);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis);

        PublicKey pubKey = cert.getPublicKey();

        Signature sig = Signature.getInstance("MD5withRSA");
        sig.initVerify(pubKey);

        sig.update(tokenString.getBytes());
        isValid = sig.verify(signature);

    } catch (FileNotFoundException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (CertificateException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    }

    return isValid;

}

From source file:com.ibm.bi.dml.parser.python.PyDMLParserWrapper.java

/**
 * This function is supposed to be called directly only from PydmlSyntacticValidator when it encounters 'import'
 * @param fileName/*from w w  w  .ja  v  a  2  s .co  m*/
 * @return null if atleast one error
 */
public DMLProgram doParse(String fileName, String dmlScript, HashMap<String, String> argVals)
        throws ParseException {
    DMLProgram dmlPgm = null;

    ANTLRInputStream in;
    try {
        if (dmlScript == null) {
            dmlScript = DMLParserWrapper.readDMLScript(fileName);
        }

        InputStream stream = new ByteArrayInputStream(dmlScript.getBytes());
        in = new org.antlr.v4.runtime.ANTLRInputStream(stream);
        //         else {
        //            if(!(new File(fileName)).exists()) {
        //               throw new ParseException("ERROR: Cannot open file:" + fileName);
        //            }
        //            in = new ANTLRInputStream(new FileInputStream(fileName));
        //         }
    } catch (FileNotFoundException e) {
        throw new ParseException("ERROR: Cannot find file:" + fileName);
    } catch (IOException e) {
        throw new ParseException("ERROR: Cannot open file:" + fileName);
    } catch (LanguageException e) {
        throw new ParseException("ERROR: " + e.getMessage());
    }

    PmlprogramContext ast = null;
    CustomDmlErrorListener errorListener = new CustomDmlErrorListener();

    try {
        PydmlLexer lexer = new PydmlLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        PydmlParser antlr4Parser = new PydmlParser(tokens);

        boolean tryOptimizedParsing = false; // For now no optimization, since it is not able to parse integer value. 

        if (tryOptimizedParsing) {
            // Try faster and simpler SLL
            antlr4Parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
            antlr4Parser.removeErrorListeners();
            antlr4Parser.setErrorHandler(new BailErrorStrategy());
            try {
                ast = antlr4Parser.pmlprogram();
                // If successful, no need to try out full LL(*) ... SLL was enough
            } catch (ParseCancellationException ex) {
                // Error occurred, so now try full LL(*) for better error messages
                tokens.reset();
                antlr4Parser.reset();
                if (fileName != null) {
                    errorListener.pushCurrentFileName(fileName);
                } else {
                    errorListener.pushCurrentFileName("MAIN_SCRIPT");
                }
                // Set our custom error listener
                antlr4Parser.addErrorListener(errorListener);
                antlr4Parser.setErrorHandler(new DefaultErrorStrategy());
                antlr4Parser.getInterpreter().setPredictionMode(PredictionMode.LL);
                ast = antlr4Parser.pmlprogram();
            }
        } else {
            // Set our custom error listener
            antlr4Parser.removeErrorListeners();
            antlr4Parser.addErrorListener(errorListener);
            errorListener.pushCurrentFileName(fileName);

            // Now do the parsing
            ast = antlr4Parser.pmlprogram();
        }
    } catch (Exception e) {
        throw new ParseException("ERROR: Cannot parse the program:" + fileName);
    }

    try {
        // Now convert the parse tree into DMLProgram
        // Do syntactic validation while converting 
        ParseTree tree = ast;
        // And also do syntactic validation
        ParseTreeWalker walker = new ParseTreeWalker();
        PydmlSyntacticValidatorHelper helper = new PydmlSyntacticValidatorHelper(errorListener);
        PydmlSyntacticValidator validator = new PydmlSyntacticValidator(helper, fileName, argVals);
        walker.walk(validator, tree);
        errorListener.popFileName();
        if (errorListener.isAtleastOneError()) {
            return null;
        }
        dmlPgm = createDMLProgram(ast);
    } catch (Exception e) {
        throw new ParseException("ERROR: Cannot translate the parse tree into DMLProgram:" + e.getMessage());
    }

    return dmlPgm;
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb./* ww w .j a  va2  s.c  o m*/
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}