Example usage for java.lang SecurityException printStackTrace

List of usage examples for java.lang SecurityException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:org.mitre.eren.model.ModelManager.java

public ModelManager(String[] args) {
    myQueue = new LinkedBlockingQueue<Element>();

    // parse the arguments
    int serverPort = 3737;
    String endpoint = "http://erenbus-gertner.mitre.org:3732/";

    try {// w  w w . j  a  v  a2s . c o  m
        Options options = new Options();

        options.addOption("p", "port", true,
                "Server port to listen on for incoming HTTP messages from the bus");
        options.addOption("u", "url", true, "Outbound URL to post HTTP messages to");
        options.addOption("l", "log", true, "Path to logfiles");
        options.addOption("s", "scale", true,
                "Population scale factor.  The populations from the scenario file are divided by this number");
        options.addOption("c", "class", true, "this is ignored");
        options.addOption("h", "help", false, "Prints this help message");

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args, true);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("ERENModel.jar", options);
            System.exit(1);
        }
        if (cmd.hasOption("p")) {
            serverPort = Integer.parseInt(cmd.getOptionValue("p"));
        }
        if (cmd.hasOption("u")) {
            endpoint = cmd.getOptionValue("u");
        }
        if (cmd.hasOption("s")) {
            scaleFactor = Integer.parseInt(cmd.getOptionValue("s"));
        }
        if (cmd.hasOption("l")) {
            String logfile = cmd.getOptionValue("l");
            FileHandler fh;
            try {
                fh = new FileHandler(logfile + "model%g.log", 10000000, 5);
                log.addHandler(fh);
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        log.log(Level.WARNING, "Caught Exception", e);
    }

    // Start the server
    messageProcessor = new InboundModelHttpController(this);
    //        InboundHttpEndpoint server = new InboundHttpEndpoint(serverPort, new InboundMessageHandler(messageProcessor));
    //        Thread st = new Thread(server, "EREN HTTP Inbound Endpoint");
    //        //st.setDaemon(true);
    //        st.start();

    // build the client
    this.delayedEventQueue = new PriorityBlockingQueue<DelayedEvent>();
    this.eventQueue = new LinkedBlockingQueue<Event>();
    Thread qt = new Thread("EREN Model Event Queue") {
        @Override
        public void run() {
            while (true) {
                try {
                    Event e = eventQueue.take();
                    e.getStateMachine().fireEvent(e.getEventName());
                } catch (InterruptedException e) {
                }
            }
        }
    };
    qt.start();

    //        client = new OutboundHttpEndpoint(endpoint);
    //        client.registerExtension(new EDXLRMExtensionFactory());
    //        client.registerExtension(new StartupExtensionFactory());
    resourceHolder = new ResourceHolder(client, sender);
}

From source file:com.baidu.cafe.local.record.WebElementRecorder.java

/**
 * use java reflect mechanism to get original WebChromeClient object
 * //from ww w  . j av  a 2  s.c om
 * @param webView
 * @return
 */
private WebChromeClient getOriginalWebChromeClient(final WebView webView) {
    WebChromeClient mWebChromeClient = null;
    try {
        if (Build.VERSION.SDK_INT > 14) {
            Object originalWebViewClassic = viewRecorder.getLocalLib().invoke(webView, "android.webkit.WebView",
                    "getWebViewProvider", new Class[] {}, new Object[] {});
            Object originalCallbackProxy = viewRecorder.getLocalLib().getField(originalWebViewClassic, null,
                    "mCallbackProxy");
            mWebChromeClient = (WebChromeClient) viewRecorder.getLocalLib().getField(originalCallbackProxy,
                    null, "mWebChromeClient");
        } else {
            mWebChromeClient = (WebChromeClient) viewRecorder.getLocalLib().invoke(webView,
                    "android.webkit.WebView", "getWebChromeClient", new Class[] {}, new Object[] {});
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    return mWebChromeClient;
}

From source file:com.baidu.cafe.local.record.WebElementRecorder.java

/**
 * @param webView/*from   ww w  . ja v  a2  s  .  c o m*/
 * @return
 */
private WebViewClient getOriginalWebViewClient(final WebView webView) {
    // save old WebViewClient
    WebViewClient mWebViewClient = null;
    try {
        // print("Build.VERSION.SDK_INT : " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT > 14) {
            Object originalWebViewClassic = viewRecorder.getLocalLib().invoke(webView, "android.webkit.WebView",
                    "getWebViewProvider", new Class[] {}, new Object[] {});
            Object originalCallbackProxy = viewRecorder.getLocalLib().getField(originalWebViewClassic, null,
                    "mCallbackProxy");
            mWebViewClient = (WebViewClient) viewRecorder.getLocalLib().getField(originalCallbackProxy, null,
                    "mWebViewClient");
        } else {
            print("getClass:" + webView.getClass());
            mWebViewClient = (WebViewClient) viewRecorder.getLocalLib().invoke(webView,
                    "android.webkit.WebView", "getWebViewClient", new Class[] {}, new Object[] {});
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return mWebViewClient;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * @see java.applet.Applet#init()/*from  w  ww . java 2s.  c  o  m*/
 */
public void init() {

    // has to be first before any gui components are created
    if (getParameter("overwriteDialogLocale") != null) {
        m_overwriteDialogLocale = getParameter("overwriteDialogLocale");
        Locale wpLocale = new Locale(m_overwriteDialogLocale);
        setLocale(wpLocale);
    }

    m_opencms = getParameter("opencms");
    m_targetUrl = getParameter("target");
    m_redirectUrl = getParameter("redirect");
    m_redirectTargetFrame = getParameter("targetframe");
    if ((m_redirectTargetFrame == null) || m_redirectTargetFrame.equals("")) {
        m_redirectTargetFrame = "explorer_files";
    }
    m_errorUrl = getParameter("error");
    m_uploadFolder = getParameter("filelist");
    m_fileFilterSelection = getParameter("filefilterselection");
    String tmpSize = getParameter("maxsize");
    if ((tmpSize != null) && (tmpSize.length() > 0)) {
        m_maxsize = Long.parseLong(tmpSize);
    }
    m_fileExtensions = getParameter("fileExtensions");
    m_colors = extractColors(getParameter("colors"));

    // setup the applet output
    m_font = new java.awt.Font(null, Font.BOLD, 12);
    m_metrics = getFontMetrics(m_font);
    m_source = getImage(getCodeBase(), "org/opencms/applet/upload/applet_source.png");
    m_target = getImage(getCodeBase(), "org/opencms/applet/upload/applet_target.png");
    m_floater = getImage(getCodeBase(), "org/opencms/applet/upload/floater.gif");

    // get the output massages in the correct language
    if (getParameter("actionOutputSelect") != null) {
        m_actionOutputSelect = getParameter("actionOutputSelect");
    }
    if (getParameter("actionOutputCount") != null) {
        m_actionOutputCount = getParameter("actionOutputCount");
    }
    if (getParameter("actionOutputCreate") != null) {
        m_actionOutputCreate = getParameter("actionOutputCreate");
    }
    if (getParameter("actionOverwriteCheck") != null) {
        m_actionOverwriteCheck = getParameter("actionOverwriteCheck");
    }
    if (getParameter("actionOutputUpload") != null) {
        m_actionOutputUpload = getParameter("actionOutputUpload");
    }
    if (getParameter("actionOutputError") != null) {
        m_actionOutputError = getParameter("actionOutputError");
    }
    if (getParameter("messageOutputUpload") != null) {
        m_messageOutputUpload = getParameter("messageOutputUpload");
    }
    if (getParameter("messageOutputAdding") != null) {
        m_messageOutputAdding = getParameter("messageOutputAdding");
    }
    if (getParameter("messageOutputErrorZip") != null) {
        m_messageOutputErrorZip = getParameter("messageOutputErrorZip");
    }
    if (getParameter("messageOutputErrorSize") != null) {
        m_messageOutputErrorSize = getParameter("messageOutputErrorSize");
    }
    if (getParameter("messageNoPreview") != null) {
        m_messageNoPreview = getParameter("messageNoPreview");
    }
    if (getParameter("errorLine1") != null) {
        m_errorLine1 = getParameter("errorLine1");
    }
    if (getParameter("certificateErrorTitle") != null) {
        m_certificateErrorTitle = getParameter("certificateErrorTitle");
    }
    if (getParameter("certificateErrorMessage") != null) {
        m_certificateErrorMessage = getParameter("certificateErrorMessage");
    }
    if (getParameter("overwriteDialogTitle") != null) {
        m_overwriteDialogTitle = getParameter("overwriteDialogTitle");
    }
    if (getParameter("overwriteDialogIntro") != null) {
        m_overwriteDialogIntro = getParameter("overwriteDialogIntro");
    }
    if (getParameter("overwriteDialogCancel") != null) {
        m_overwriteDialogCancel = getParameter("overwriteDialogCancel");
    }
    if (getParameter("overwriteDialogOk") != null) {
        m_overwriteDialogOk = getParameter("overwriteDialogOk");
    }
    if (getParameter("clientFolder") != null) {
        m_clientFolder = getParameter("clientFolder");
    }

    m_certificateAccepted = true;
    try {
        // set log factory to default log factory, otherwise commons logging detection will fail with an exception 
        System.setProperty(org.apache.commons.logging.LogFactory.FACTORY_PROPERTY,
                org.apache.commons.logging.LogFactory.FACTORY_DEFAULT);
    } catch (SecurityException e) {
        // this indicates the applet certificate has not been accepted
        m_certificateAccepted = false;
        e.printStackTrace();
    }
}

From source file:org.apache.directory.fortress.core.AdminMgrConsole.java

/**
 * Adds a feature to the User attribute of the AdminMgrConsole object
 *//*from  ww  w  . jav a2  s  . com*/
void addUser() {
    User ue = new User();

    try {
        ReaderUtil.clearScreen();
        System.out.println("Enter userId:");
        ue.setUserId(ReaderUtil.readLn());
        System.out.println("Enter user's common name (cn):");
        String cn = ReaderUtil.readLn();
        System.out.println("Enter user's surname (sn):");
        String sn = ReaderUtil.readLn();
        ue.setSn(sn);
        ue.setCn(cn);
        System.out.println("Enter pw");
        ue.setPassword(ReaderUtil.readLn().toCharArray());
        System.out.println("Enter User's description field");
        ue.setDescription(ReaderUtil.readLn());
        System.out.println("Enter organization unit, blank for default");
        ue.setOu(ReaderUtil.readLn());

        System.out.println("Do you want to set temporal constraints on User - Y or N");
        String choice = ReaderUtil.readLn();
        if (choice != null && choice.equalsIgnoreCase("Y")) {
            enterTemporal(ue);
        }

        System.out.println("Do you want to set posix account attributes on User - Y or N");
        choice = ReaderUtil.readLn();
        if (choice != null && choice.equalsIgnoreCase("Y")) {
            enterPosixAccount(ue);
        }

        System.out.println("Enter Role name (or NULL to skip):");
        String val = ReaderUtil.readLn();
        for (int i = 0; val != null && val.length() > 0; i++) {
            UserRole userRole = new UserRole();
            userRole.setName(val);
            userRole.setUserId(ue.getUserId());
            ue.setRole(userRole);
            System.out.println("Do you want to set temporal constraints on User - Y or N");
            choice = ReaderUtil.readLn();
            if (choice != null && choice.equalsIgnoreCase("Y")) {
                enterTemporal(userRole);
            }

            System.out.println("Enter next name (or NULL if done entering roles):");
            val = ReaderUtil.readLn();
        }

        System.out.println("Enter prop key (or NULL to skip):");
        String key = ReaderUtil.readLn();
        for (int i = 0; key != null && key.length() > 0; i++) {
            System.out.println("Enter prop val:");
            val = ReaderUtil.readLn();
            ue.addProperty(key, val);
            System.out.println("Enter next prop key (or NULL if done entering properties)");
            key = ReaderUtil.readLn();
        }

        System.out.println("Enter password policy (or NULL to skip):");
        String policy = ReaderUtil.readLn();
        if (StringUtils.isNotEmpty(policy)) {
            ue.setPwPolicy(policy);
        }
        /*
                    ue.setAddress(new Address());
                    ue.getAddress().setAddress("123 Test Ln");
                    ue.getAddress().setAddress("Suite 1");
                    ue.getAddress().setAddress("c/o resident");
                    ue.getAddress().setCity("TestCity");
                    ue.getAddress().setCountry("US");
                    ue.getAddress().setPostalCode("72113");
                    ue.getAddress().setState("AR");
                    ue.setPhone("111-222-3333");
                    ue.setPhone("222-222-3333");
                    ue.setMobile("333-222-3333");
                    ue.setMobile("444-222-3333");
        */
        User ue2 = am.addUser(ue);
        if (CollectionUtils.isNotEmpty(ue.getRoles())) {
            for (UserRole uRole : ue.getRoles()) {
                am.assignUser(uRole);
            }
        }
        System.out.println("userId [" + ue2.getUserId() + "]");
        System.out.println("internalId [" + ue2.getInternalId() + "]");
        System.out.println("user description [" + ue2.getDescription() + "]");
        System.out.println("user common name [" + ue2.getCn() + "]");
        System.out.println("user surname [" + ue2.getSn() + "]");
        System.out.println("organizational unit [" + ue2.getOu() + "]");
        System.out.println("has been added");
        System.out.println("ENTER to continue");
    } catch (SecurityException e) {
        LOG.error("addUser caught SecurityException rc=" + e.getErrorId() + ", msg=" + e.getMessage(), e);
    } catch (Exception e) {
        LOG.error("addUser caught Exception=" + e);
        e.printStackTrace();
    }
    ReaderUtil.readChar();
}

From source file:com.vuze.android.remote.SessionInfo.java

private void openTorrent_perms(Activity activity, Uri uri) {
    try {// w  ww  . j a  v a2 s .c  o m
        InputStream stream = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String realPath = PaulBurkeFileUtils.getPath(activity, uri);
            if (realPath != null) {
                String meh = realPath.startsWith("/") ? "file://" + realPath : realPath;
                stream = activity.getContentResolver().openInputStream(Uri.parse(meh));
            }
        }
        if (stream == null) {
            ContentResolver contentResolver = activity.getContentResolver();
            stream = contentResolver.openInputStream(uri);
        }
        openTorrent(activity, uri.toString(), stream);
    } catch (SecurityException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
        String s = "Security Exception trying to access <b>" + uri + "</b>";
        Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
        String s = "<b>" + uri + "</b> not found";
        if (e.getCause() != null) {
            s += ". " + e.getCause().getMessage();
        }
        Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show();
    }
}

From source file:com.canappi.connector.yp.yhere.SearchView.java

public void viewDidLoad() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        Set<String> keys = extras.keySet();
        for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
            String key = iter.next();
            Class c = SearchView.class;
            try {
                Field f = c.getDeclaredField(key);
                Object extra = extras.get(key);
                String value = extra.toString();
                f.set(this, value);
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from ww  w. j av  a  2  s  .c o m
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {

    }

    searchViewIds = new HashMap();
    searchViewValues = new HashMap();

    isUserDefault = false;

    resultsListView = (ListView) findViewById(R.id.resultsTable);
    resultsAdapter = new ResultsEfficientAdapter(this);

    businessNameArray = new ArrayList<String>();

    latitudeArray = new ArrayList<String>();

    longitudeArray = new ArrayList<String>();

    listingIdArray = new ArrayList<String>();

    phoneArray = new ArrayList<String>();

    callArray = new ArrayList<String>();

    streetArray = new ArrayList<String>();

    cityArray = new ArrayList<String>();
    resultsListView.setAdapter(resultsAdapter);
    didSelectViewController();

}

From source file:com.frostwire.android.gui.NotificationUpdateDemon.java

private void updatePermanentStatusNotification() {
    if (!ConfigurationManager.instance()
            .getBoolean(Constants.PREF_KEY_GUI_ENABLE_PERMANENT_STATUS_NOTIFICATION)) {
        return;/*  w  w  w.  j a  v  a 2 s  . c om*/
    }

    if (notificationViews == null || notificationObject == null) {
        LOG.warn("Notification views or object are null, review your logic");
        return;
    }

    // number of uploads (seeding) and downloads
    TransferManager transferManager;

    try {
        transferManager = TransferManager.instance();
    } catch (IllegalStateException btEngineNotReadyException) {
        return;
    }

    if (transferManager != null) {
        int downloads = transferManager.getActiveDownloads();
        int uploads = transferManager.getActiveUploads();
        if (downloads == 0 && uploads == 0) {
            NotificationManager manager = (NotificationManager) mParentContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) {
                try {
                    manager.cancel(Constants.NOTIFICATION_FROSTWIRE_STATUS);
                } catch (SecurityException ignored) {
                    // possible java.lang.SecurityException
                }
            }
            return; // quick return
        }
        //  format strings
        String sDown = UIUtils.rate2speed(transferManager.getDownloadsBandwidth() / 1024);
        String sUp = UIUtils.rate2speed(transferManager.getUploadsBandwidth() / 1024);
        // Transfers status.
        notificationViews.setTextViewText(R.id.view_permanent_status_text_downloads, downloads + " @ " + sDown);
        notificationViews.setTextViewText(R.id.view_permanent_status_text_uploads, uploads + " @ " + sUp);
        final NotificationManager notificationManager = (NotificationManager) mParentContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            try {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel(
                            Constants.FROSTWIRE_NOTIFICATION_CHANNEL_ID, "FrostWire",
                            NotificationManager.IMPORTANCE_MIN);
                    channel.setSound(null, null);
                    notificationManager.createNotificationChannel(channel);
                }
                notificationManager.notify(Constants.NOTIFICATION_FROSTWIRE_STATUS, notificationObject);
            } catch (SecurityException ignored) {
                // possible java.lang.SecurityException
                ignored.printStackTrace();
            } catch (Throwable ignored2) {
                // possible android.os.TransactionTooLargeException
                ignored2.printStackTrace();
            }
        }
    }
}

From source file:au.com.onegeek.lambda.core.CommandRunner.java

/**
 * Find the assertion class implementor and invoke the call using reflection.
 * // ww w. j  a  v  a2s  .  co m
 * @param testCommand
 */
public void runCommand(TestCommand testCommand) {
    String keyword = testCommand.getCommand();
    logger.debug("Looking for method with name: " + testCommand.getCommand());

    // Create Test Case w\
    Object object = null;
    Method method = null;

    // Determine argument types
    Class[] argTypes = new Class[testCommand.getParameters().length];
    int k = 0;
    for (k = 0; k < testCommand.getParameters().length; k++) {

        // Check if there is a number hidden in the args list
        // Currently, although most of the Lambda implementation supports Object params
        // The conversion into a class (JavassistTestBuilderImpl) turns them back into 
        // Strings. 

        // TODO: set locale?
        /* NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
         Number number;
         try {
         number = format.parse((String) testCommand.getParameters()[k]);
         testCommand.getParameters()[k] = number;
                 
         // Looks like it ALWAYS comes out of here as long
         // Apache commons to the rescue? Surely there is a library that does this better
         // TODO: fix this
         if (number.getClass().getSimpleName().equalsIgnoreCase("long")) {
            argTypes[k] = long.class;               
         }
         else if (number.getClass().getSimpleName().equalsIgnoreCase("double")) {
            argTypes[k] = double.class;               
         }
         else if (number.getClass().getSimpleName().equalsIgnoreCase("float")) {
            argTypes[k] = float.class;               
         }
        } catch (Exception e) {
         // TODO Auto-generated catch block
         //e.printStackTrace();
        }*/

        //          if (argTypes[k] == null) {
        argTypes[k] = testCommand.getParameters()[k].getClass();
        //          }
        logger.debug("Argument value: " + testCommand.getParameters()[k]);
        logger.debug("Argument class: " + argTypes[k]);
    }

    logger.info("looking for providers...");

    // Find the implementing class of the method
    for (Object provider : this.lambda.getAssertionProviders()) {
        try {
            logger.info("getting method....");
            method = provider.getClass().getMethod(keyword, argTypes);
            logger.info("got one!");
            object = provider;
        } catch (SecurityException e) {
            logger.debug("Not allowed to call method " + keyword + " from Provider <"
                    + provider.getClass().getName() + "> ");
        } catch (NoSuchMethodException e) {
            for (Object object2 : argTypes) {
                logger.debug("Method: " + keyword + ": Arg type: " + object2);
            }
            logger.debug(
                    "Method: " + keyword + " not found in Provider <" + provider.getClass().getName() + "> ");
        }
    }

    logger.info("Checknig if we found a provider");

    if (object == null) {
        logger.error("cannot find provider of method " + keyword);
        fail("Cannot find a provider of method: '" + keyword + "'");
    } else {
        logger.debug("Found source object for method, object: <" + object.toString() + ">");
    }

    // Invoke method
    Object result = "not set";
    try {
        logger.info("Invoking method '" + keyword + "' on object");
        result = method.invoke(object, testCommand.getParameters());
    } catch (IllegalArgumentException e) {
        fail("Method '" + keyword + "' illegal argument exception: " + e.getMessage());
    } catch (IllegalAccessException e) {
        fail("Method '" + keyword + "' illegal acess exception: " + e.getMessage());
    } catch (InvocationTargetException e) {
        // This is usually a failed Assertion from an AssertionProvider
        logger.debug("InvocationTargetException, usually a failed assertion: ");
        if (logger.isErrorEnabled()) {
            e.printStackTrace();
        }
        fail("Method '" + keyword + "' InvocationTarget exception: " + e.getMessage());

        // TODO: remove\handle this better
        e.printStackTrace();
    } catch (AssertionError e) {
        logger.error("Assertion fail: " + e.getMessage());
    }

    logger.debug("output from reflected method: " + result);
}

From source file:org.sakaiproject.qna.logic.test.AnswerLogicImplTest.java

/**
 * Test add answer to question//from  w ww.  j a  v a 2s  .c  o m
 */
@Test
public void testSaveAnswer() {

    String answerText = "Test add answer text";

    // Add answer with an invalid userid
    try {
        externalLogicStub.currentUserId = USER_LOC_3_NO_UPDATE_1;
        QnaAnswer answer = new QnaAnswer();
        answer.setAnswerText(answerText);
        answer.setQuestion(tdp.question3_location1);
        answer.setAnonymous(true);
        answer.setPrivateReply(false);
        answerLogic.saveAnswer(answer, LOCATION1_ID);
        Assert.fail("Should have thrown exception");
    } catch (SecurityException e) {
        Assert.assertNotNull(e);
    }

    // Add answer with an invalid configuration (anonymous reply not
    // allowed)
    try {
        externalLogicStub.currentUserId = USER_UPDATE;
        QnaAnswer answer = new QnaAnswer();
        answer.setAnswerText(answerText);
        answer.setQuestion(tdp.question3_location1);
        answer.setAnonymous(true);
        answer.setPrivateReply(false);
        answerLogic.saveAnswer(answer, LOCATION1_ID);
        ;
        Assert.fail("Should have caught the exception");
    } catch (QnaConfigurationException e) {
        Assert.assertNotNull(e);
    }

    // Add answer with valid configuration
    try {
        externalLogicStub.currentUserId = USER_LOC_3_UPDATE_1;

        QnaAnswer answer = new QnaAnswer();
        answer.setAnswerText(answerText);
        answer.setQuestion(tdp.question1_location3);
        answer.setAnonymous(true);
        answer.setPrivateReply(false);
        answerLogic.saveAnswer(answer, LOCATION3_ID);

        QnaQuestion question = questionLogic.getQuestionById(tdp.question1_location3.getId());

        Assert.assertEquals(2, question.getAnswers().size());
        boolean found = false;
        for (QnaAnswer answer1 : question.getAnswers()) {
            Assert.assertNotNull(answer1.getId());
            if (answer1.getAnswerText().equals(answerText))
                found = true;
        }
        Assert.assertTrue(found);

    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Should not have caught exception");
    }
}