Example usage for java.lang Exception getClass

List of usage examples for java.lang Exception getClass

Introduction

In this page you can find the example usage for java.lang Exception getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:pmp.springmail.TestDrive.java

void sendEmailViaPlainMail(String text) {
    Authenticator authenticator = new Authenticator() {

        @Override/*  w  ww .  j  ava2s  .com*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USER, PASS);
        }
    };

    Session session = Session.getInstance(props, authenticator);
    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject("Plain JavaMail Test");
        message.setText(DATE_FORMAT.format(new Date()) + " " + text);

        Transport.send(message);

    } catch (Exception e) {
        System.err.println(e.getClass().getSimpleName() + " " + e.getMessage());
    }
}

From source file:org.pentaho.proxy.creators.userdetailsservice.ProxyUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    try {//from ww w .j  a  v a2s.  c  o m
        Object result = ReflectionUtils.invokeMethod(loadUserByNameMethod, sourceObject,
                new Object[] { username });
        if (result != null) {
            return new ProxyUserDetails(result);
        } else {
            logger.warn(
                    "Got a null from calling the method loadUserByUsername( String username ) of UserDetailsService: "
                            + sourceObject
                            + ". This is an interface violation beacuse it is specified that loadUserByUsername method should never return null. Throwing a UsernameNotFoundException.");
        }
    } catch (Exception e) {
        if (e.getClass().getName().equals(FULL_NAME_SS4_USERNOTFOUNDEXCEPTION)) {
            throw new UsernameNotFoundException(username + " not found", e);
        } else {
            logger.error(e.getMessage(), e);
        }
    }
    throw new UsernameNotFoundException(username);
}

From source file:org.mitre.oauth2.web.OAuth2ExceptionHandler.java

@ExceptionHandler(OAuth2Exception.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
    logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
    return providerExceptionHandler.translate(e);
}

From source file:au.edu.anu.portal.portlets.basiclti.adapters.BasicLTIAdapterFactory.java

/**
 * Instantiate the desired implementation
 * //from   www.  j  a  v a2  s  .c om
 * @param className      name of class
 * @return
 */
public IBasicLTIAdapter newAdapter(String className) {

    IBasicLTIAdapter adapter = null;
    try {
        adapter = (IBasicLTIAdapter) Class.forName(className).newInstance();
    } catch (Exception e) {
        log.error("Error instantiating class: " + e.getClass() + ":" + e.getMessage());
    }
    return adapter;
}

From source file:pl.bristleback.server.bristle.action.exception.handler.GenericActionExecutionExceptionHandler.java

@Override
public Object handleException(Exception e, ActionExecutionContext context) {
    return new ExceptionResponse(e.getClass().getSimpleName(), context.getStage());
}

From source file:com.github.javarch.persistence.aop.JavarchPersistenceExceptionTranslate.java

private void throwsDataBaseException(Exception ex) {
    LOG.debug("Tranduzindo exceo {} em DabaBaseException", ex.getClass().getName());
    DataBaseException dbException = new DataBaseException(ex.getMessage(), ex);
    throw dbException;
}

From source file:com.revorg.goat.IndexManager.java

/**
 * Creates documents inside of the Lucene Index
 *
 * @param driverName        Database Driver
 * @param sourceURL         Database Connection URL
 * @param dbUsername        Database Username
 * @param dbPassword        Database Password
 * @param execSQL           T-SQL//from   w  w w . j a v a 2 s  .  co m
 * @throws Exception
 * @return ActionResult
 */
public static String indexDatabase(String indexPath, String driverName, String sourceURL, String dbUsername,
        String dbPassword, String execSQL) {
    //
    execSQL = execSQL.replace("from", "FROM");
    execSQL = execSQL.replace("FROM", " FROM ");
    String returnResult = "";
    String workPath = indexPath + dirSep + "working" + new Random().nextInt(100000) + dirSep;
    String configFile = indexPath + dirSep + "config" + dirSep + "dsschema.xml";
    String tempHTMLDir = tempDirectory + dirSep + "htmlIndexing" + dirSep + Utilities.CreateUUID() + dirSep;

    File workDir = new File(workPath);
    File schemaFile = new File(configFile);
    File htmlIndexing = new File(tempHTMLDir);

    // Declare the JDBC objects.
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;

    try {

        //Get Configuration File
        if (schemaFile.exists() == false) {

            ActionResultError = "DB Schema File (" + schemaFile + ")Does Not Exists";
            System.out.println(ActionResultError);
            ActionResult = "Failure ";
            return ActionResult + ActionResultError;
        }

        //Make Sure Working Director Does Not Exists
        if (workDir.exists()) {
            ActionResultError = "Failure to create index: " + workPath + " The index/directory already exists:";
            ActionResult = "Failure";
            return ActionResult + ActionResultError;
        } else {
            //Create Temporary Index
            IndexManager.createIndex(workPath);
        }

        //Load the driver class
        Class.forName(driverName);
        System.out.println("Driver Loaded");
        Properties prop = new Properties();
        prop.setProperty("user", dbUsername);
        prop.setProperty("password", dbPassword);

        DriverManager.setLoginTimeout(5); //Set Login Time
        con = DriverManager.getConnection(sourceURL, prop);

        //Result Set
        // Create and execute an SQL statement that returns some data.
        String SQL = execSQL;
        stmt = con.createStatement();
        rs = stmt.executeQuery(SQL);
        rsMetaData = rs.getMetaData();
        int columns = rsMetaData.getColumnCount();
        String[] indexTypeArray = new String[columns];
        String[] columnNamesArray = new String[columns]; //Set array Length to Column Length from Meta Data
        String[] columnTypesArray = new String[columns]; //Set array Length to Column Length from Meta Data

        int primaryKeyPos = 0;
        int triggerPos = 0;
        String triggerType = "";
        boolean triggerExists = false;
        boolean primaryExists = false;

        XMLReader readerXML = new XMLReader(); //XML Reader Class   
        //Drop into an array to keep from parsing XML more than once
        for (int i = 0; i < columns; i++) {
            indexTypeArray[i] = readerXML.getNodeValueByFile(configFile, i, "indextype");
            columnNamesArray[i] = readerXML.getNodeValueByFile(configFile, i, "columnname");
            columnTypesArray[i] = readerXML.getNodeValueByFile(configFile, i, "columntype");
            //Get Trigger Position 
            if (indexTypeArray[i].equalsIgnoreCase("PrimaryKey") == true) {
                primaryExists = true;
                primaryKeyPos = i + 1;
            }
            //Update or Delete Trigger
            if (indexTypeArray[i].equalsIgnoreCase("triggerUpdate") == true
                    || indexTypeArray[i].equalsIgnoreCase("triggerDelete") == true) {
                triggerExists = true;
                triggerPos = i + 1;

                //Update or Delete Trigger
                if (indexTypeArray[i].equalsIgnoreCase("triggerUpdate") == true) {
                    triggerType = "Update";
                } else {
                    triggerType = "Delete";
                }

            }
        }

        //Create Temporary HTML Indexing Folder
        if (htmlIndexing.exists()) {
            ActionResultError = "Failure to create directory: " + htmlIndexing
                    + " The index/directory already exists:";
            ActionResult = "Failure";
            return ActionResult + ActionResultError;
        } else {
            //Create Temporary Index
            IndexManager.createIndex(tempHTMLDir);
        }

        Date start = new Date();
        //StandardAnalyzer new StandardAnalyzer() = new StandardAnalyzer();    //Initialize Class
        IndexWriter writer = new IndexWriter(workPath, new StandardAnalyzer(), false,
                IndexWriter.MaxFieldLength.LIMITED);
        System.out.println("Indexing to directory '" + workPath + "'...");

        String dynamicSQL = "";
        int currentRow = 0; //Process Next Rows                   
        while (rs.next()) {
            //Create Dynamic SQL
            if (primaryKeyPos != 0) {
                if (currentRow > 0) {
                    dynamicSQL = dynamicSQL + ",";
                }
                dynamicSQL = dynamicSQL + rs.getInt(primaryKeyPos);
            }

            String docStatus = createDocument(writer, rs, columnNamesArray, indexTypeArray, tempHTMLDir);

            //On Failure
            if (docStatus.substring(0, 4).equalsIgnoreCase("Fail")) {
                IndexManager.deleteIndex(tempHTMLDir);

                IndexManager.deleteIndex(workPath);
                return docStatus;
            }

            //Create Actual Document  
            ++currentRow;
        }

        returnResult = "Successfully indexing of " + Integer.toString(currentRow) + " documents.";

        //Get Table From String
        //System.out.println(execSQL);
        String updateTable = "";
        String[] words = execSQL.split(" ");
        int wordPos = 0;
        int tablePos = 0;
        for (String word : words) {
            ++wordPos;
            if (word.equalsIgnoreCase("FROM") == true) {
                tablePos = wordPos + 2;
            }
            if (tablePos == wordPos) {
                updateTable = word;
                break;
            }
        }

        //Must be Records
        if (triggerExists && primaryExists && updateTable.length() > 0 && currentRow != 0) {

            if (triggerType.equalsIgnoreCase("Update") == true) {
                dynamicSQL = "update " + updateTable + " set " + columnNamesArray[triggerPos - 1] + " =1 where "
                        + columnNamesArray[primaryKeyPos - 1] + " in (" + dynamicSQL + ");";
            } else {
                dynamicSQL = "delete from " + updateTable + " where " + columnNamesArray[primaryKeyPos - 1]
                        + " in (" + dynamicSQL + ");";
            }
            System.out.println(dynamicSQL);
            stmt.execute(dynamicSQL);
        }

        System.out.println("Optimizing..." + currentRow + " Documents");

        //Close Working Writer
        writer.close();

        //Merge Indexes;
        IndexManager.mergeIndexes(indexPath, workPath);
        //Optimization Done Inside Merge

        //Delete Working Folder
        IndexManager.deleteIndex(workPath);
        IndexManager.deleteIndex(tempHTMLDir);

        Date end = new Date();
        System.out.println(end.getTime() - start.getTime() + " total milliseconds: = "
                + ((end.getTime() - start.getTime()) / 1000) + " Seconds");

        ActionResult = returnResult;
        rs.close(); //Close Result Set
        con.close();
        return ActionResult;

    }

    catch (Exception e) {
        IndexManager.deleteIndex(workPath); //Delete Working Folder
        IndexManager.deleteIndex(tempHTMLDir);

        e.printStackTrace();
        ActionResult = "Failure: " + e + " caught a " + e.getClass() + " with message: " + e.getMessage();
        return ActionResult + ActionResultError;

    }
}

From source file:de.tudarmstadt.lt.lm.app.ListServices.java

/**
 * /* w w  w  .j  a v  a2  s.  c o  m*/
 */
public ListServices(String[] args) {
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?"));
    opts.addOption(OptionBuilder.withLongOpt("host").withArgName("hostname").hasArg()
            .withDescription("specifies the hostname on which the rmi registry listens (default: localhost)")
            .create("h"));
    opts.addOption(OptionBuilder.withLongOpt("port").withArgName("port-number").hasArg().withDescription(String
            .format("specifies the port on which rmi registry listens (default: %d)", Registry.REGISTRY_PORT))
            .create("p"));

    try {
        CommandLine cmd = new ExtendedGnuParser(true).parse(opts, args);
        if (cmd.hasOption("help"))
            CliUtils.print_usage_quit(StartLM.class.getSimpleName(), opts, null, 0);
        _port = Integer.parseInt(cmd.getOptionValue("port", String.valueOf(Registry.REGISTRY_PORT)));
        _host = cmd.getOptionValue("host", "localhost");
    } catch (Exception e) {
        LOG.error("{}: {}", e.getClass().getSimpleName(), e.getMessage());
        CliUtils.print_usage_quit(StartLM.class.getSimpleName(), opts,
                String.format("%s: %s%n", e.getClass().getSimpleName(), e.getMessage()), 1);
    }
}

From source file:com.stormpath.sample.web.resolvers.SampleSimpleExceptionResolver.java

@Override
protected ModelAndView getModelAndView(String viewName, Exception ex) {
    logger.error(String.format("Error of type [%s]. Exception reason: [%s]", ex.getClass().getSimpleName(),
            ex.getMessage()), ex);//from   w w w  .  j  a  va 2s .  c o m
    return super.getModelAndView(viewName, ex);
}

From source file:com.hillert.botanic.controller.BotanicControllerAdvice.java

@ExceptionHandler(value = AuthenticationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)/* w  ww. ja v a  2  s  .c  o  m*/
@ResponseBody
public ErrorMessage handleAuthenticationException(Exception e) {
    return new ErrorMessage(new Date(), HttpStatus.FORBIDDEN.value(), e.getClass().getName(), e.getMessage());
}