Example usage for java.lang RuntimeException printStackTrace

List of usage examples for java.lang RuntimeException printStackTrace

Introduction

In this page you can find the example usage for java.lang RuntimeException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.xlsx4j.org.apache.poi.ss.usermodel.FractionFormat.java

public String format(Number num) {

    final double doubleValue = num.doubleValue();

    final boolean isNeg = (doubleValue < 0.0f) ? true : false;
    final double absDoubleValue = Math.abs(doubleValue);

    final double wholePart = Math.floor(absDoubleValue);
    final double decPart = absDoubleValue - wholePart;
    if (wholePart + decPart == 0) {
        return "0";
    }// w w w  .j a  v a 2  s.co m

    // if the absolute value is smaller than 1 over the exact or maxDenom
    // you can stop here and return "0"
    // reciprocal is result of an int devision ... and so it's nearly always 0
    // double reciprocal = 1/Math.max(exactDenom,  maxDenom);
    // if (absDoubleValue < reciprocal) {
    //    return "0";
    // }

    //this is necessary to prevent overflow in the maxDenom calculation
    if (Double.compare(decPart, 0) == 0) {

        StringBuilder sb = new StringBuilder();
        if (isNeg) {
            sb.append("-");
        }
        sb.append((int) wholePart);
        return sb.toString();
    }

    SimpleFraction fract = null;
    try {
        //this should be the case because of the constructor
        if (exactDenom > 0) {
            fract = SimpleFraction.buildFractionExactDenominator(decPart, exactDenom);
        } else {
            fract = SimpleFraction.buildFractionMaxDenominator(decPart, maxDenom);
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
        return Double.toString(doubleValue);
    }

    StringBuilder sb = new StringBuilder();

    //now format the results
    if (isNeg) {
        sb.append("-");
    }

    //if whole part has to go into the numerator
    if ("".equals(wholePartFormatString)) {
        int trueNum = (fract.getDenominator() * (int) wholePart) + fract.getNumerator();
        sb.append(trueNum).append("/").append(fract.getDenominator());
        return sb.toString();
    }

    //short circuit if fraction is 0 or 1
    if (fract.getNumerator() == 0) {
        sb.append(Integer.toString((int) wholePart));
        return sb.toString();
    } else if (fract.getNumerator() == fract.getDenominator()) {
        sb.append(Integer.toString((int) wholePart + 1));
        return sb.toString();
    }
    //as mentioned above, this ignores the exact space formatting in Excel
    if (wholePart > 0) {
        sb.append(Integer.toString((int) wholePart)).append(" ");
    }
    sb.append(fract.getNumerator()).append("/").append(fract.getDenominator());
    return sb.toString();
}

From source file:com.simiacryptus.mindseye.test.unit.SerializationTest.java

@Nullable
@Override/*  ww  w.ja  va  2 s  . com*/
public ToleranceStatistics test(@Nonnull final NotebookOutput log, @Nonnull final Layer layer,
        final Tensor... inputPrototype) {
    log.h1("Serialization");
    log.p("This apply will demonstrate the key's JSON serialization, and verify deserialization integrity.");

    String prettyPrint = "";
    log.h2("Raw Json");
    try {
        prettyPrint = log.eval(() -> {
            final JsonObject json = layer.getJson();
            @Nonnull
            final Layer echo = Layer.fromJson(json);
            if (echo == null)
                throw new AssertionError("Failed to deserialize");
            if (layer == echo)
                throw new AssertionError("Serialization did not copy");
            if (!layer.equals(echo))
                throw new AssertionError("Serialization not equal");
            echo.freeRef();
            return new GsonBuilder().setPrettyPrinting().create().toJson(json);
        });
        @Nonnull
        String filename = layer.getClass().getSimpleName() + "_" + log.getName() + ".json";
        log.p(log.file(prettyPrint, filename,
                String.format("Wrote Model to %s; %s characters", filename, prettyPrint.length())));
    } catch (RuntimeException e) {
        e.printStackTrace();
        Util.sleep(1000);
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        Util.sleep(1000);
    }
    log.p("");
    @Nonnull
    Object outSync = new Object();
    if (prettyPrint.isEmpty() || prettyPrint.length() > 1024 * 64)
        Arrays.stream(SerialPrecision.values()).parallel().forEach(precision -> {
            try {
                @Nonnull
                File file = new File(log.getResourceDir(), log.getName() + "_" + precision.name() + ".zip");
                layer.writeZip(file, precision);
                @Nonnull
                final Layer echo = Layer.fromZip(new ZipFile(file));
                getModels().put(precision, echo);
                synchronized (outSync) {
                    log.h2(String.format("Zipfile %s", precision.name()));
                    log.p(log.link(file, String.format("Wrote Model apply %s precision to %s; %.3fMiB bytes",
                            precision, file.getName(), file.length() * 1.0 / (0x100000))));
                }
                if (!isPersist())
                    file.delete();
                if (echo == null)
                    throw new AssertionError("Failed to deserialize");
                if (layer == echo)
                    throw new AssertionError("Serialization did not copy");
                if (!layer.equals(echo))
                    throw new AssertionError("Serialization not equal");
            } catch (RuntimeException e) {
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            } catch (ZipException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    return null;
}

From source file:com.stormpath.tooter.controller.LoginController.java

@RequestMapping(method = RequestMethod.GET, value = "/emailVerificationTokens")
public String accountVerification(@RequestParam("sptoken") String token,
        @ModelAttribute("customer") User customer, BindingResult result) {

    String returnStr = "login";

    try {// www  . j  a va  2s  .  c  om

        stormpath.getTenant().verifyAccountEmail(token);
        returnStr = "redirect:/login/message?loginMsg=accVerified";

    } catch (RuntimeException re) {

        result.addError(new ObjectError("userName", re.getMessage()));
        re.printStackTrace();
    }

    return returnStr;

}

From source file:xiaofei.library.datastorage.database.DbService.java

public void executeInTransaction(Runnable runnable) {
    if (runnable == null) {
        throw new IllegalArgumentException();
    }//from   w  w  w  . j  a va  2 s .c om
    try {
        mDb.beginTransaction();
        try {
            runnable.run();
            mDb.setTransactionSuccessful();
        } finally {
            mDb.endTransaction();
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
}

From source file:com.aimfire.gallery.service.PhotoProcessor.java

@Override
protected void onHandleIntent(Intent intent) {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    /*//w w w .j  a  v a  2  s.c  o m
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    Bundle extras = intent.getExtras();
    if (extras == null) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleIntent: error, wrong parameter");
        return;
    }

    String filename1 = extras.getString("lname");
    String filename2 = extras.getString("rname");

    String creatorName = extras.getString("creator");
    String creatorPhotoUrl = extras.getString("photo");

    float scale = extras.getFloat(MainConsts.EXTRA_SCALE);

    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    String[] stereoPath = MediaScanner.getImgPairPaths(filename1, filename2);

    if (stereoPath == null) {
        /*
         * something seriously wrong here - can't find matching image
         */
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleEvent: cannot locate stereo image pair");
        reportError(MediaScanner.getProcessedSbsPath(filename1));
        return;
    }

    if (BuildConfig.DEBUG)
        Log.d(TAG,
                "onHandleIntent:stereoPath[0]=" + stereoPath[0] + ",stereoPath[1]=" + stereoPath[1]
                        + ",stereoPath[2]=" + stereoPath[2] + ",stereoPath[3]=" + stereoPath[3]
                        + ",stereoPath[4]=" + stereoPath[4]);

    /*
     * now do auto alignment and store images as full width sbs jpgs. 
     * original left/right images will be removed unless save flag
     * is set to true (for debugging)
     */
    boolean[] success = new boolean[] { false, false };
    try {
        success = p.getInstance().b(stereoPath[0], stereoPath[1], stereoPath[2], scale, isFrontCamera);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }

    if (!success[0]) {
        reportError(stereoPath[2]);
    } else {
        saveThumbnail(stereoPath[2], MainConsts.MEDIA_3D_THUMB_PATH + (new File(stereoPath[2])).getName());

        MediaScanner.insertExifInfo(stereoPath[2], "name=" + creatorName + "photourl=" + creatorPhotoUrl);

        reportResult(stereoPath[2], success[1]);
    }

    File leftFrom = new File(stereoPath[0]);
    File rightFrom = new File(stereoPath[1]);

    if (!BuildConfig.DEBUG) {
        leftFrom.delete();
        rightFrom.delete();
    } else {
        File leftTo = new File(stereoPath[3]);
        File rightTo = new File(stereoPath[4]);

        leftFrom.renameTo(leftTo);
        rightFrom.renameTo(rightTo);
    }
}

From source file:com.expedia.seiso.domain.service.impl.ItemServiceImpl.java

/**
 * Using {@link Propagation.NEVER} because we don't want a single error to wreck the entire operation.
 *//*from   ww w .j  ava2  s.c o  m*/
@Override
@Transactional(propagation = Propagation.NEVER)
public SaveAllResponse saveAll(@NonNull Class itemClass, @NonNull List<? extends Item> items,
        boolean mergeAssociations) {

    val numItems = items.size();
    val itemClassName = itemClass.getSimpleName();
    log.info("Batch saving {} items ({})", numItems, itemClass.getSimpleName());

    val errors = new ArrayList<SaveAllError>();

    for (val item : items) {
        try {
            // Have to doInTransaction() since calling save() happens behind the transactional proxy.
            // Also, see http://stackoverflow.com/questions/5568409/java-generics-void-void-types
            txTemplate.execute(new TransactionCallback<Void>() {

                @Override
                public Void doInTransaction(TransactionStatus status) {
                    save(item, mergeAssociations);
                    return null;
                }
            });
        } catch (RuntimeException e) {
            e.printStackTrace();
            val message = e.getClass() + ": " + e.getMessage();
            errors.add(new SaveAllError(item.itemKey(), message));
        }
    }

    val numErrors = errors.size();
    if (numErrors == 0) {
        log.info("Batch saved {} items ({}) with no errors", numItems, itemClassName);
    } else {
        log.warn("Batch saved {} items ({}) with {} errors: {}", numItems, itemClassName, numErrors, errors);
    }

    return new SaveAllResponse(numItems, numErrors, errors);
}

From source file:xiaofei.library.datastorage.database.DbService.java

@Override
public <T> T getObject(Class<T> clazz, String objectIds) {
    T result = null;/*from  w  w  w. ja v  a 2s  .  c  o  m*/
    Cursor cursor = mDb.query(DbConst.TABLE_NAME, null,
            generateEquation(DbConst.CLASS_ID, mAnnotationProcessor.getClassId(clazz)) + " and "
                    + generateEquation(DbConst.OBJECT_ID, objectIds),
            null, null, null, null);
    if (cursor.moveToNext()) {
        String data = cursor.getString(cursor.getColumnIndex(DbConst.OBJECT_DATA));
        try {
            result = mCoder.decode(data, clazz);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }
    cursor.close();
    return result;
}

From source file:TopicReplier.java

/**
 * Handle the message./*  w w w .  ja va2s.c om*/
 * (as specified in the javax.jms.MessageListener interface).
 *
 * IMPORTANT NOTE: We must follow the design paradigm for JMS
 * synchronous requests.  That is, we must:
 *   - get the message
 *   - look for the header specifying JMSReplyTo
 *   - send a reply to the topic specified there.
 * Failing to follow these steps might leave the originator
 * of the request waiting forever.
 *
 * OPTIONAL BEHAVIOR: The following actions taken by the
 * message handler represent good programming style, but are
 * not required by the design paradigm for JMS requests.
 *   - set the JMSCorrelationID (tying the response back to
 *     the original request.
 *   - use transacted session "commit" so receipt of request
 *     won't happen without the reply being sent.
 *
 */
public void onMessage(javax.jms.Message aMessage) {
    try {
        // Cast the message as a text message.
        javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage;

        // This handler reads a single String from the
        // message and prints it to the standard output.
        try {
            String string = textMessage.getText();
            System.out.println("[Request] " + string);

            // Check for a ReplyTo topic
            javax.jms.Topic replyTopic = (javax.jms.Topic) aMessage.getJMSReplyTo();
            if (replyTopic != null) {
                // Send the modified message back.
                javax.jms.TextMessage reply = session.createTextMessage();
                if (imode == UPPERCASE)
                    reply.setText("Transformed " + string + " to all uppercase: " + string.toUpperCase());
                else
                    reply.setText("Transformed " + string + " to all lowercase " + string.toLowerCase());
                reply.setJMSCorrelationID(aMessage.getJMSMessageID());
                replier.send(replyTopic, reply);
                session.commit();
            }
        } catch (javax.jms.JMSException jmse) {
            jmse.printStackTrace();
        }
    } catch (java.lang.RuntimeException rte) {
        rte.printStackTrace();
    }
}

From source file:org.columba.mail.main.MailMain.java

/**
 *
 *///from  www.  j a  v a 2 s.  co m
public void postStartup() {
    // Check default mail client
    checkDefaultClient();

    // Show first time Account Wizard
    if (MailConfig.getInstance().getAccountList().count() == 0) {
        new AccountWizardLauncher().launchWizard(true);
    }

    // Check Internet Connection
    if (MailConfig.getInstance().getAccountList().count() > 0) {
        try {
            IncomingItem testConnection = MailConfig.getInstance().getAccountList().getDefaultAccount()
                    .getIncomingItem();
            ConnectionStateImpl.getInstance().setTestConnection(testConnection.get("host"),
                    testConnection.getInteger("port"));
            ConnectionStateImpl.getInstance().checkPhysicalState();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    // Activate all Virtual Folders
    ActivateVirtualFolderCommand.activateAll((IMailFolder) FolderTreeModel.getInstance().getRoot());
}

From source file:Talk.java

/**
 * Handle the message//from w ww .j  a  va  2  s  .  c  om
 * (as specified in the javax.jms.MessageListener interface).
 */
public void onMessage(javax.jms.Message aMessage) {
    try {
        // Cast the message as a text message.
        // Otherwise report that invalid message arrived.
        if (aMessage instanceof javax.jms.TextMessage) {
            javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage;

            // This handler reads a single String from the
            // message and prints it to the standard output.
            try {
                String string = textMessage.getText();
                System.out.println(string);
            } catch (javax.jms.JMSException jmse) {
                jmse.printStackTrace();
            }
        } else {
            System.out.println("Warning: A message was discarded because it could not be processed "
                    + "as a javax.jms.TextMessage.");
        }

    } catch (java.lang.RuntimeException rte) {
        rte.printStackTrace();
    }
}