Example usage for java.lang NullPointerException printStackTrace

List of usage examples for java.lang NullPointerException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:edu.uark.spARK.SwipeDismissListViewTouchListener.java

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if (mViewWidth < 2) {
        mViewWidth = mListView.getWidth();
    }/*from   w  w w .  j a  va  2  s  . c o m*/
    switch (motionEvent.getActionMasked()) {
    case MotionEvent.ACTION_DOWN: {
        mPaused = false;
        longClickActive = false;
        //                if (mPaused) {
        //                    return false;
        //                }

        // TODO: ensure this is a finger, and set a flag

        // Find the child view that was touched (perform a hit test)
        Rect rect = new Rect();
        int childCount = mListView.getChildCount();
        int[] listViewCoords = new int[2];
        mListView.getLocationOnScreen(listViewCoords);
        int x = (int) motionEvent.getRawX() - listViewCoords[0];
        int y = (int) motionEvent.getRawY() - listViewCoords[1];
        View child;

        //ignore header views
        for (int i = 1; i < childCount; i++) {
            child = mListView.getChildAt(i);
            child.getHitRect(rect);
            if (rect.contains(x, y)) {
                mDownView = child;
                break;
            }
        }
        if (mDownView != null) {
            mDownView = mDownView.findViewById(R.id.table);
            mDownX = motionEvent.getRawX();
            //TODO: really need to figure out why npe is happening here
            try {
                mDownPosition = mListView.getPositionForView(mDownView);
            } catch (NullPointerException npe) {
                //why does this keep happening?
                npe.printStackTrace();
            }
            if (mCallbacks.canDismiss(mDownPosition)) {
                mVelocityTracker = VelocityTracker.obtain();
                mVelocityTracker.addMovement(motionEvent);
            } else {
                mDownView = null;
            }
        }
        view.onTouchEvent(motionEvent);
        return true;
    }

    case MotionEvent.ACTION_UP: {
        if (longClickActive) {
            RelativeLayout darkenTop = (RelativeLayout) mListView.getRootView()
                    .findViewById(R.id.darkenScreenTop);
            ImageView darkenBottom = (ImageView) mListView.getRootView().findViewById(R.id.darkenScreenBottom);
            darkenTop.animate().alpha(0).setDuration(mAnimationTime).setListener(null);
            darkenBottom.animate().alpha(0).setDuration(mAnimationTime).setListener(null);
            if (mVelocityTracker == null) {
                break;
            }
            float deltaX = motionEvent.getRawX() - mDownX;
            mVelocityTracker.addMovement(motionEvent);
            mVelocityTracker.computeCurrentVelocity(1000);
            float velocityX = mVelocityTracker.getXVelocity();
            float absVelocityX = Math.abs(velocityX);
            float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
            boolean dismiss = false;
            boolean dismissRight = false;
            if (Math.abs(deltaX) > mViewWidth / 2) {
                dismiss = true;
                dismissRight = deltaX > 0;
            } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                    && absVelocityY < absVelocityX) {
                // dismiss only if flinging in the same direction as dragging
                dismiss = (velocityX < 0) == (deltaX < 0);
                dismissRight = mVelocityTracker.getXVelocity() > 0;
            }
            if (dismiss) {
                // dismiss
                dismiss(mDownView, mDownPosition, dismissRight);
            } else {
                // cancel
                mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null);
            }
            mVelocityTracker.recycle();
            mVelocityTracker = null;
            mDownX = 0;
            mDownView = null;
            mDownPosition = ListView.INVALID_POSITION;
            mSwiping = false;
        }
        break;
    }

    case MotionEvent.ACTION_CANCEL: {
        longClickActive = false;
        mPaused = false;
        RelativeLayout darkenTop = (RelativeLayout) mListView.getRootView().findViewById(R.id.darkenScreenTop);
        ImageView darkenBottom = (ImageView) mListView.getRootView().findViewById(R.id.darkenScreenBottom);

        darkenTop.animate().alpha(0).setDuration(mAnimationTime).setListener(null);
        darkenBottom.animate().alpha(0).setDuration(mAnimationTime).setListener(null);

        if (mVelocityTracker == null) {
            break;
        }

        if (mDownView != null) {
            // cancel
            mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null);
        }
        mVelocityTracker.recycle();
        mVelocityTracker = null;
        mDownX = 0;
        mDownView = null;
        mDownPosition = ListView.INVALID_POSITION;
        mSwiping = false;
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        if (mVelocityTracker == null || mPaused) {
            break;
        }
        if (longClickActive) {
            mVelocityTracker.addMovement(motionEvent);
            float deltaX = motionEvent.getRawX() - mDownX;
            //the if statement is allowing the listview to scroll until a sufficient deltaX is made, while we want swiping immediately 
            //                        if (Math.abs(deltaX) > mSlop) {
            mSwiping = true;
            mListView.requestDisallowInterceptTouchEvent(true);

            // Cancel ListView's touch (un-highlighting the item) which is not what we want
            MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
            cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                    | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
            mListView.onTouchEvent(cancelEvent);
            cancelEvent.recycle();
            //                        }
            if (mSwiping) {

                mDownView.setTranslationX(deltaX);
                //we don't want the alpha to change
                //                    mDownView.setAlpha(Math.max(0.15f, Math.min(1f,
                //                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                return true;
            }
        }
        break;
    }
    }
    return false;
}

From source file:com.sshtools.j2ssh.transport.kex.GssGroup1Sha1.java

/**
 *
 *
 * @param clientId// w w w.  j  a v  a 2 s  .c o m
 * @param serverId
 * @param clientKexInit
 * @param serverKexInit
 *
 * @throws IOException
 * @throws AlgorithmOperationException
 * @throws KeyExchangeException
 */
public void performClientExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit,
        boolean firstPacketFollows, boolean useFirstPacket, boolean firstExch) throws IOException {
    try {
        log.info("Starting client side key exchange.");
        transport.getMessageStore().registerMessage(SshMsgKexGssInit.SSH_MSG_KEXGSS_INIT,
                SshMsgKexGssInit.class);

        transport.getMessageStore().registerMessage(SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE,
                SshMsgKexGssContinue.class);
        transport.getMessageStore().registerMessage(SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE,
                SshMsgKexGssComplete.class);

        transport.getMessageStore().registerMessage(SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY,
                SshMsgKexGssHostKey.class);
        transport.getMessageStore().registerMessage(SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR,
                SshMsgKexGssError.class);
        this.clientId = clientId;
        this.serverId = serverId;
        this.clientKexInit = clientKexInit;
        this.serverKexInit = serverKexInit;

        //int minBits = g.bitLength();
        //int maxBits = q.bitLength();
        //Random rnd = ConfigurationLoader.getRND();
        // Generate a random bit count for the random x value

        /*int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat())
         + minBits);
              x = new BigInteger(genBits, rnd);
              // Calculate e
              e = g.modPow(x, p);*/
        try {
            DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
            dhKeyPairGen.initialize(dhSkipParamSpec);

            KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair();
            dhKeyAgreement.init(dhKeyPair.getPrivate());
            x = ((DHPrivateKey) dhKeyPair.getPrivate()).getX();
            e = ((DHPublicKey) dhKeyPair.getPublic()).getY();
        } catch (InvalidKeyException ex) {
            throw new AlgorithmOperationException("Failed to generate DH value");
        } catch (InvalidAlgorithmParameterException ex) {
            throw new AlgorithmOperationException("Failed to generate DH value");
        }
        //C calls GSS_Init_sec_context!
        log.info("Generating shared context with server...");
        GlobusGSSManagerImpl globusgssmanagerimpl = new GlobusGSSManagerImpl();

        HostAuthorization gssAuth = new HostAuthorization(null);
        GSSName targetName = gssAuth.getExpectedName(null, hostname);
        GSSCredential gsscredential = null;
        GSSContext gsscontext = null;
        if (theCredential == null) {
            gsscredential = UserGridCredential.getUserCredential(properties);
            theCredential = gsscredential;
        } else {
            gsscredential = theCredential;
            try {
                ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential().verify();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (GlobusCredentialException e) {
                e.printStackTrace();
                javax.swing.JOptionPane.showMessageDialog(properties.getWindow(),
                        "The credentials that you authenticated with have expired, please re-authenticate.",
                        "GSI-SSH Terminal", javax.swing.JOptionPane.WARNING_MESSAGE);
                gsscredential = UserGridCredential.getUserCredential(properties);
                theCredential = gsscredential;
            }
        }
        gsscontext = globusgssmanagerimpl.createContext(targetName, GSSConstants.MECH_OID, gsscredential,
                GSSCredential.DEFAULT_LIFETIME);

        gsscontext.requestCredDeleg(true);
        gsscontext.requestMutualAuth(true);
        gsscontext.requestInteg(true);
        //gsscontext.requestAnonymity(false);
        // gsscontext.requestReplayDet(false);
        //gsscontext.requestSequenceDet(false);
        // gsscontext.requestConf(false);
        Object type = GSIConstants.DELEGATION_TYPE_LIMITED;
        String cur = "None";
        if (properties instanceof SshToolsConnectionProfile) {
            cur = ((SshToolsConnectionProfile) properties)
                    .getApplicationProperty(SshTerminalPanel.PREF_DELEGATION_TYPE, "Full");
            if (cur.equals("full")) {
                type = GSIConstants.DELEGATION_TYPE_FULL;
            } else if (cur.equals("limited")) {
                type = GSIConstants.DELEGATION_TYPE_LIMITED;
            } else if (cur.equals("none")) {
                type = GSIConstants.DELEGATION_TYPE_LIMITED;
                gsscontext.requestCredDeleg(false);
            }
        }
        log.debug("Enabling delegation setting: " + cur);
        ((ExtendedGSSContext) gsscontext).setOption(GSSConstants.DELEGATION_TYPE, type);

        log.debug("Starting GSS token exchange.");
        byte abyte2[] = new byte[0];
        Object obj = null;
        boolean firsttime = true;
        hostKey = null;
        do {
            if (gsscontext.isEstablished())
                break;
            byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
            if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without mutual authentication in gss-group1-sha1-* key exchange.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getIntegState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without integrety protection in gss-group1-sha1-* key exchange.");
            }
            if (abyte3 != null) {
                if (firsttime) {
                    SshMsgKexGssInit msg = new SshMsgKexGssInit(e, /*bytearraywriter1.toByteArray()*/abyte3);
                    transport.sendMessage(msg, this);
                } else {
                    SshMsgKexGssContinue msg = new SshMsgKexGssContinue(
                            /*bytearraywriter1.toByteArray()*/abyte3);
                    transport.sendMessage(msg, this);
                }
            } else {
                throw new KeyExchangeException("Expecting a non-zero length token from GSS_Init_sec_context.");
            }
            if (!gsscontext.isEstablished()) {
                int[] messageId = new int[3];
                messageId[0] = SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY;
                messageId[1] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE;
                messageId[2] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
                SshMessage msg = transport.readMessage(messageId);
                if (msg.getMessageId() == SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY) {
                    if (!firsttime) {
                        throw new KeyExchangeException(
                                "Not expecting a SSH_MSG_KEXGS_HOSTKEY message at this time.");
                    }
                    SshMsgKexGssHostKey reply = (SshMsgKexGssHostKey) msg;
                    hostKey = reply.getHostKey();
                    messageId = new int[2];
                    messageId[0] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE;
                    messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
                    msg = transport.readMessage(messageId);
                    if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR)
                        errormsg(msg);
                } else if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR) {
                    errormsg(msg);
                }
                SshMsgKexGssContinue reply = (SshMsgKexGssContinue) msg;
                abyte2 = reply.getToken();
            }
            firsttime = false;
        } while (true);
        log.debug("Sending gssapi exchange complete.");
        int[] messageId = new int[2];
        messageId[0] = SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE;
        messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
        SshMessage msg = transport.readMessage(messageId);
        if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR)
            errormsg(msg);
        SshMsgKexGssComplete reply = (SshMsgKexGssComplete) msg;
        if (reply.hasToken()) {
            ByteArrayReader bytearrayreader1 = new ByteArrayReader(reply.getToken());
            abyte2 = bytearrayreader1.readBinaryString();
            byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
            if (abyte3 != null) {
                throw new KeyExchangeException("Expecting zero length token.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without mutual authentication in gss-group1-sha1-* key exchange.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getIntegState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without integrety protection in gss-group1-sha1-* key exchange.");
            }
        }

        byte per_msg_token[] = reply.getMIC();
        f = reply.getF();

        // Calculate diffe hellman k value
        secret = f.modPow(x, p);

        // Calculate the exchange hash
        calculateExchangeHash();

        gsscontext.verifyMIC(per_msg_token, 0, per_msg_token.length, exchangeHash, 0, exchangeHash.length,
                null);

        gssContext = gsscontext;
    } catch (GSSException g) {
        String desc = g.toString();
        if (desc.startsWith(
                "GSSException: Failure unspecified at GSS-API level (Mechanism level: GSS Major Status: Authentication Failed")
                && desc.indexOf("an unknown error occurred") >= 0) {
            throw new KeyExchangeException(
                    "Error from GSS layer: \n Probably due to your proxy credential being expired or signed by a CA unknown by the server or your clock being set wrong.",
                    g);
        } else {
            if (desc.indexOf("From Server") >= 0) {
                throw new KeyExchangeException("GSS Error from server", g);
            } else {
                throw new KeyExchangeException("Error from GSS layer", g);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:ca.mudar.parkcatcher.ui.fragments.DetailsFragment.java

/**
 * Implementation of SearchMessageHandler.OnMessageHandledListener
 *///from  www .j a  va  2 s  .c o  m
@Override
public void OnMessageHandled(Message msg) {
    final Bundle b = msg.getData();

    mView.findViewById(R.id.details_progress_address).setVisibility(View.GONE);

    if (b.getInt(Const.KEY_BUNDLE_REVERSE_GEOCODER) == Const.BUNDLE_SEARCH_ADDRESS_SUCCESS) {
        TextView addressUi = (TextView) mView.findViewById(R.id.details_address);
        final String desc = b.getString(Const.KEY_BUNDLE_ADDRESS_DESC);
        addressUi.setText(desc);
        addressUi.setVisibility(View.VISIBLE);

        final int indexOfSeparator = desc.indexOf(Const.LINE_SEPARATOR);
        if (indexOfSeparator > 0) {
            mFavoriteLabel = desc.substring(0, indexOfSeparator);
        } else {
            mFavoriteLabel = desc;
        }

    } else {
        /**
         * Address not found! Display error message.
         */
        try {
            ((ParkingApp) getActivity().getApplicationContext()).showToastText(R.string.toast_address_error,
                    Toast.LENGTH_SHORT);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

}

From source file:it.acubelab.batframework.systemPlugins.AIDAAnnotator.java

@Override
public Set<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {

    /* Lazy connection if the connection made by the constructor failed.*/
    if (!AidaRMIClientManager.isConnected())
        setupConnection();//from  w w w.  j av  a 2  s. c  o m

    Set<AIDATag> res = new HashSet<AIDATag>();
    List<String> titlesToPrefetch = new Vector<String>();

    //lastTime = Calendar.getInstance().getTimeInMillis();
    AidaParsePackage input = new AidaParsePackage(text, "" + text.hashCode(), settings);
    AidaResultsPackage result = null;
    try {
        result = AidaRMIClientManager.parse(input);
    } catch (java.lang.NullPointerException e) {
        System.out
                .println("Caught exception while processing text:\n [text beginning]\n" + text + "[text end]");
        throw e;
    } catch (Exception e) {
        System.out
                .println("Caught exception while processing text:\n [text beginning]\n" + text + "[text end]");
        e.printStackTrace();
        throw new AnnotationException(e.getMessage());
    }
    //lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;
    //System.out.println(result.getOverallRunTime()+ "\t" + lastTime+"ms");

    if (result == null) {
        String noSpaceText = CharUtils.trim(text).toString();
        System.out.println("NULL RESULT: " + noSpaceText.substring(0, Math.min(10, noSpaceText.length())));
    }
    if (result != null) {
        Matcher time1 = Pattern.compile("^(\\d*)ms$").matcher(result.getOverallRunTime());
        Matcher time2 = Pattern.compile("^(\\d*)s, (\\d*)ms$").matcher(result.getOverallRunTime());
        Matcher time3 = Pattern.compile("^(\\d*)m, (\\d*)s, (\\d*)ms$").matcher(result.getOverallRunTime());
        Matcher time4 = Pattern.compile("^(\\d*)h, (\\d*)m, (\\d*)s, (\\d*)ms$")
                .matcher(result.getOverallRunTime());
        Matcher time5 = Pattern.compile("^(\\d*)d, (\\d*)h, (\\d*)m, (\\d*)s, (\\d*)ms$")
                .matcher(result.getOverallRunTime());
        if (time1.matches())
            lastTime = Integer.parseInt(time1.group(1));
        else if (time2.matches())
            lastTime = Integer.parseInt(time2.group(1)) * 1000 + Integer.parseInt(time2.group(2));
        else if (time3.matches())
            lastTime = Integer.parseInt(time3.group(1)) * 1000 * 60 + Integer.parseInt(time3.group(2)) * 1000
                    + Integer.parseInt(time3.group(3));
        else if (time4.matches())
            lastTime = Integer.parseInt(time4.group(1)) * 1000 * 60 * 60
                    + Integer.parseInt(time4.group(2)) * 1000 * 60 + Integer.parseInt(time4.group(3)) * 1000
                    + Integer.parseInt(time4.group(4));
        else if (time5.matches())
            lastTime = Integer.parseInt(time5.group(1)) * 1000 * 60 * 60 * 24
                    + Integer.parseInt(time5.group(2)) * 1000 * 60 * 60
                    + Integer.parseInt(time5.group(3)) * 1000 * 60 + Integer.parseInt(time5.group(4)) * 1000
                    + Integer.parseInt(time5.group(5));
        else
            throw new AnnotationException("Time value returned by AIDA [" + result.getOverallRunTime()
                    + "] does not match the pattern.");

        DisambiguationResults disRes = result.getDisambiguationResults();
        for (ResultMention mention : disRes.getResultMentions()) {
            ResultEntity resEntity = disRes.getBestEntity(mention);

            int position = mention.getCharacterOffset();
            int length = mention.getMention().length();
            String pageTitleEscaped = resEntity.getEntity();
            String pageTitleUnescaped = StringEscapeUtils.unescapeJava(pageTitleEscaped);
            float score = (float) resEntity.getDisambiguationScore();
            if (pageTitleEscaped.equals("--NME--")) //Aida could not identify the topic.
                break;

            res.add(new AIDATag(position, length, pageTitleUnescaped, score));
            titlesToPrefetch.add(pageTitleUnescaped);
        }
    }

    /** Prefetch wids of titles*/
    try {
        api.prefetchTitles(titlesToPrefetch);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException(e.getMessage());
    }

    /** Convert to Scored Tags*/
    Set<ScoredAnnotation> resScoredAnnotations = new HashSet<ScoredAnnotation>();
    for (AIDATag t : res) {
        int wid;
        try {
            wid = api.getIdByTitle(t.title);
        } catch (IOException e) {
            e.printStackTrace();
            throw new AnnotationException(e.getMessage());
        }
        if (wid != -1)
            resScoredAnnotations.add(new ScoredAnnotation(t.position, t.length, wid, t.score));
    }
    return resScoredAnnotations;
}

From source file:kr.co.cashqc.MainActivity.java

public void findLocation() {
    mDialog.show();/* w  w  w  .j  a va 2  s  . com*/
    mLocationUtil.start();
    TimerTask timerTask = new TimerTask() {
        public void run() {
            mHandler.post(new Runnable() {
                public void run() {
                    try {
                        String address;
                        address = mLocationUtil.getAddress(mLocationUtil.getLastLocation().getLatitude(),
                                mLocationUtil.getLastLocation().getLongitude());

                        // Log.d("tag", mAddressText.getText().toString() +
                        // " "
                        // + mAddressText.getText().toString().length());

                        mAddressText.setVisibility(View.VISIBLE);

                        mLatitude = mLocationUtil.getLastLocation().getLatitude();
                        mLongitude = mLocationUtil.getLastLocation().getLongitude();

                        mAddressText.setText(address);

                        mGpsFlag = true;

                        mDialog.dismiss();
                    } catch (NullPointerException e) {
                        Log.d("JAY", "gps exception");
                        e.printStackTrace();

                        mAddressText.setText("<-  ?   ? .");

                        mDialog.dismiss();

                        mGpsFlag = false;
                    }
                }
            });
        }
    };

    if (mLocationUtil.isRunLocationUtil) {
        mLocationUtil.stop();
    }

    Timer timer = new Timer();
    timer.schedule(timerTask, 1000);
}

From source file:displayStructureAsPDFTable.java

public void drawStructure(IAtomContainer mol, int cnt) {

    // do aromaticity detection
    try {/*from  ww  w  .  j  a v a2s  .co  m*/
        CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
        cdke.printStackTrace();
    }
    mol = addHeteroHydrogens(mol);
    r2dm = new Renderer2DModel();
    renderer = new Renderer2D(r2dm);
    Dimension screenSize = new Dimension(this.width, this.height);
    setPreferredSize(screenSize);
    r2dm.setBackgroundDimension(screenSize); // make sure it is synched with the JPanel size
    setBackground(r2dm.getBackColor());

    try {
        StructureDiagramGenerator sdg = new StructureDiagramGenerator();
        sdg.setMolecule((IMolecule) mol);
        sdg.generateCoordinates();
        this.mol = sdg.getMolecule();

        r2dm.setDrawNumbers(false);
        r2dm.setUseAntiAliasing(true);
        r2dm.setColorAtomsByType(doColor);
        r2dm.setShowAromaticity(true);
        r2dm.setShowAromaticityInCDKStyle(false);
        r2dm.setShowReactionBoxes(false);
        r2dm.setKekuleStructure(false);
        r2dm.setShowExplicitHydrogens(withH);
        r2dm.setShowImplicitHydrogens(true);
        GeometryTools.translateAllPositive(this.mol);
        GeometryTools.scaleMolecule(this.mol, getPreferredSize(), this.scale);
        GeometryTools.center(this.mol, getPreferredSize());
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    this.frame.getContentPane().add(this);
    this.frame.pack();

    String filename;
    if (cnt < 10)
        filename = this.odir + "/img00" + cnt + this.suffix;
    else if (cnt < 100)
        filename = this.odir + "/img0" + cnt + this.suffix;
    else
        filename = this.odir + "/img" + cnt + this.suffix;

    if (oformat.equalsIgnoreCase("png") || oformat.equalsIgnoreCase("jpeg")) {
        BufferedImage img;
        try {
            img = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_RGB);
            //                img = (BufferedImage) createImage(this.getSize().width, this.getSize().height);
            Graphics2D snapGraphics = (Graphics2D) img.getGraphics();
            this.paint(snapGraphics);
            File graphicsFile = new File(filename);
            ImageIO.write(img, oformat, graphicsFile);
        } catch (NullPointerException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    } else if (oformat.equalsIgnoreCase("pdf")) {
        File file = new File(filename);
        Rectangle pageSize = new Rectangle(this.getSize().width, this.getSize().height);
        Document document = new Document(pageSize);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            Image awtImage = createImage(this.getSize().width, this.getSize().height);
            Graphics snapGraphics = awtImage.getGraphics();
            paint(snapGraphics);

            com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(awtImage, null);
            pdfImage.setAbsolutePosition(0, 0);
            cb.addImage(pdfImage);

        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        document.close();
    } else if (oformat.equalsIgnoreCase("svg")) {
        /*
             try {
        SVGWriter cow = new SVGWriter(new FileWriter(filename));
        if (cow != null) {
            cow.writeAtomContainer(mol);
            cow.close();
        }
             } catch (IOException ioe) {
        ioe.printStackTrace();
             } catch (CDKException cdke) {
        cdke.printStackTrace();
             }
        */
    }
}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Changes the font size to what the user selects (between 8-30)
 *//*from   ww  w .j  av  a2 s  .  c om*/
private void changeFontSize() {
    Integer[] nums = new Integer[23];
    for (int i = 8; i <= 30; i++) {
        nums[i - 8] = i;
    }
    try {
        int size = (int) JOptionPane.showInputDialog(this, "Choose a font size:", "Font Size",
                JOptionPane.PLAIN_MESSAGE, null, nums, Main.getState().getSettings().getFontSize());
        FontUIResource font = new FontUIResource("Dialog", Font.BOLD, size);

        Main.setUIFont(font);
        Main.getState().getSettings().setFontSize(size);
        SwingUtilities.updateComponentTreeUI(gr);

        for (JInternalFrame i : desktop.getAllFrames())
            i.pack();

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:fm.krui.kruifm.KRUIScheduleActivity.java

/**
 * Parses a Google Calendar JSONObject and builds a list of Shows, which are assigned the passed category value.
 * @param calObj Google Calendar JSONObject to parse
 * @param category category value as an int
 *//*  w w  w .ja  v  a2  s .co  m*/
private void parseShowData(JSONObject calObj, int category) {

    /* When dayOfWeek != dayCache, we have changed weekdays, so we must change storage location in the list. Initial
    value will match with Sunday shows */
    int dayCache = 1;

    /* dayList contains all of the shows for the current weekday. When weekday is changed, dayList is stored
    into the master showList, and the list is wiped clean to be used again. */
    ArrayList<Show> dayList = new ArrayList<Show>();

    // Map used to convert text weekday values to integers
    HashMap<String, Integer> weekdayToIntMap = new HashMap<String, Integer>();
    String[] weekdays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    for (int j = 0; j < 7; j++) {
        weekdayToIntMap.put(weekdays[j], j + 1);
    }

    try {
        JSONArray calendarArray = calObj.getJSONArray("items"); // "items" array stored here

        // For each JSON Object in the array, extract all necessary data
        for (int i = 0; i < calendarArray.length(); i++) {
            JSONObject o = calendarArray.getJSONObject(i);
            JSONObject startObject = o.getJSONObject("start");
            JSONObject endObject = o.getJSONObject("end");
            String calId = o.getString("id");
            String title = o.getString("summary");
            String description = "";
            if (o.isNull("description") == false) {
                description = o.getString("description");
            }
            String link = o.getString("htmlLink");
            String startUTC = startObject.getString("dateTime");
            String endUTC = endObject.getString("dateTime");

            // Parse UTC results to get day of week and human readable time
            String startTime = Utils.convertTime(startUTC, "yyyy-MM-dd'T'HH:mm:ssZ",
                    TimeZone.getTimeZone("UTC"), "hh a", TimeZone.getTimeZone("America/Chicago"));
            String endTime = Utils.convertTime(endUTC, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("UTC"),
                    "hh a", TimeZone.getTimeZone("America/Chicago"));
            String dayOfWeekText = Utils.convertTime(startUTC, "yyyy-MM-dd'T'hh:mm:ssZ",
                    TimeZone.getTimeZone("UTC"), "E", TimeZone.getTimeZone("America/Chicago"));

            // Get number of minutes from midnight to the start of this show to determine top margin of event
            // Formula:
            // 24 hour start time n is in [1,24], * 60 minutes in an hour to determine hour many minutes until the top of the hour
            // Check minutes of starting time to see if the event starts somewhere other than the top of the hour. If minutes > 0, add it to the hour calculation.
            String startMinuteString = Utils.convertTime(startUTC, "yyyy-MM-dd'T'HH:mm:ssZ",
                    TimeZone.getTimeZone("UTC"), "HH m", TimeZone.getTimeZone("America/Chicago"));

            // Split result on whitespace to separate hours and minutes. a[0] = minutes until the top of the hour this show starts, a[1] contains offset minutes if they exist.
            String[] a = startMinuteString.split("\\s+");
            int startMinutes = (Integer.parseInt(a[0]) * 60) + Integer.parseInt(a[1]);
            //Log.v(TAG, "Start time for show " + title + "is " + startMinutes);

            // Do the same for end time
            String endMinuteString = Utils.convertTime(endUTC, "yyyy-MM-dd'T'HH:mm:ssZ",
                    TimeZone.getTimeZone("UTC"), "HH m", TimeZone.getTimeZone("America/Chicago"));
            String[] b = endMinuteString.split("\\s+");
            int endMinutes = (Integer.parseInt(b[0]) * 60) + Integer.parseInt(b[1]);
            //Log.v(TAG, "End time for show " + title + " is " + endMinutes);

            int dayOfWeekInt = weekdayToIntMap.get(dayOfWeekText);

            // Construct a show object and write this event to the show list
            Show show = new Show(calId, 1, title, startTime, endTime, startMinutes, endMinutes, link,
                    description, dayOfWeekInt);

            // Set this show object's category value to color it correctly in ScheduleFragment.
            // Using the key in downloadShowData, the correct category is always the k+1th value.
            show.setCategory(category);

            // Enqueue this show onto the Priority Queue
            Log.v(TAG, "Adding " + show.getTitle() + " to the priority queue.");
            Log.v(TAG, "Show category is: " + show.getCategory());
            pq.add(show);
        }

    } catch (NullPointerException e) {
        Log.e(TAG, "No events were available to parse.");

    } catch (JSONException e) {
        Log.e(TAG, "Error parsing Programming Information from JSON. ");
        e.printStackTrace();
    }

}

From source file:com.cypress.cysmart.GATTDBFragments.GattDetailsFragment.java

@Override
public void dialog0kPressed(String result) {
    displayTimeandDate();/*  www  .  j  a  va  2 s  . c o m*/
    byte[] convertedBytes = convertingTobyteArray(result);
    // Displaying the hex and ASCII values
    displayHexValue(convertedBytes);
    displayASCIIValue(mHexValue.getText().toString());

    // Writing the hexValue to the characteristics
    try {
        BluetoothLeService.writeCharacteristicGattDb(mReadCharacteristic, convertedBytes);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:com.taobao.luaview.view.indicator.circle.CirclePageIndicator.java

public boolean onTouchEvent(MotionEvent ev) {
    if (super.onTouchEvent(ev)) {
        return true;
    }// www.  j  av a  2s .  co  m
    if ((mViewPager == null) || (getActualCount() == 0)) {
        return false;
    }

    final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        mLastMotionX = ev.getX();
        break;

    case MotionEvent.ACTION_MOVE: {
        final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        final float x = MotionEventCompat.getX(ev, activePointerIndex);
        final float deltaX = x - mLastMotionX;

        if (!mIsDragging) {
            if (Math.abs(deltaX) > mTouchSlop) {
                mIsDragging = true;
            }
        }

        if (mIsDragging) {
            mLastMotionX = x;
            if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
                mViewPager.fakeDragBy(deltaX);
            }
        }

        break;
    }

    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
        if (!mIsDragging) {
            final int count = getActualCount();
            final int width = getWidth();
            final float halfWidth = width / 2f;
            final float sixthWidth = width / 6f;

            if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
                if (action != MotionEvent.ACTION_CANCEL) {
                    mViewPager.setCurrentItem(mCurrentPage - 1);
                }
                return true;
            } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
                if (action != MotionEvent.ACTION_CANCEL) {
                    mViewPager.setCurrentItem(mCurrentPage + 1);
                }
                return true;
            }
        }

        mIsDragging = false;
        mActivePointerId = INVALID_POINTER;
        if (mViewPager.isFakeDragging()) {
            //fix monkey bug
            try {
                mViewPager.endFakeDrag();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        break;

    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        mLastMotionX = MotionEventCompat.getX(ev, index);
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }

    case MotionEventCompat.ACTION_POINTER_UP:
        final int pointerIndex = MotionEventCompat.getActionIndex(ev);
        final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
        if (pointerId == mActivePointerId) {
            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
            mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
        }
        mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }

    return true;
}