Example usage for java.net URISyntaxException printStackTrace

List of usage examples for java.net URISyntaxException printStackTrace

Introduction

In this page you can find the example usage for java.net URISyntaxException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:nl.surfsara.warcexamples.hadoop.ldps.LDPRMapper.java

@Override
public void map(LongWritable key, WarcRecord value, Context context) throws IOException, InterruptedException {
    context.setStatus(Counters.CURRENT_RECORD + ": " + key.get());

    String targetURI = value.header.warcTargetUriStr;

    if (null == targetURI || "".equals(targetURI)) {
        context.getCounter(Counters.NUM_NO_IP).increment(1);
    } else {//from w  ww . jav  a 2s.c om
        try {
            warcTargetUriStrHost = new URI(targetURI).getHost();
        } catch (URISyntaxException e) {
            logger.error(e);
        }
    }

    // Only process text/plain content
    if ("text/plain".equals(value.header.contentTypeStr)
            && !(prevWarcTargetUriStr.equals(warcTargetUriStrHost))) {
        context.getCounter(Counters.NUM_TEXT_RECORDS).increment(1);
        // Get the text payload
        Payload payload = value.getPayload();

        prevWarcTargetUriStr = warcTargetUriStrHost;

        if (payload == null || temp > 50) {
            // NOP
        } else {

            String warcContent = IOUtils.toString(payload.getInputStreamComplete());
            if (warcContent == null && "".equals(warcContent)) {
                // NOP
            } else {
                // Classify text
                //               warcContent = warcContent.substring(0, Math.min(warcContent.length(), MAXLEN));

                int i = warcContent.indexOf(' ');
                if (i > 0) {
                    String word = warcContent.substring(0, i);
                    //                  context.write(new Text(word), new LongWritable(3));   
                    logger.info("LOGGER: tmpdir: " + word);
                    LOG.info("LOG: tmpdir: " + word);
                }

                try {
                    Detector detector = DetectorFactory.create();
                    detector.append(warcContent);
                    context.write(new Text(detector.detect()), new LongWritable(1));
                } catch (LangDetectException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    logger.error(e);
                }
            }
            temp++;
        }
    }
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;/*from   w  w  w  . j av a2 s  .c o m*/
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            // CHECK RESPONSE FOR SUCCESS!!
            if (!failed && response != null
                    && response.matches(res.getString(R.string.video_bin_API_good_re))) {
                // We got back HTTP response with valid URL
                Log.d(TAG, " video bin got back URL " + response);

            } else {
                Log.d(TAG, " video bin got eror back:\n" + response);
                failed = true;
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);

                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(true);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java

private static InputStream loadPropertiesMessagesDefaults() {
    // get the default file
    URL msgURL = AlfrescoController.class.getResource("/messages.properties");
    if (msgURL == null) {
        if (logger.isErrorEnabled()) {
            logger.error(//from www  .j a v a  2  s .  c o  m
                    "Configuration file 'messages.properties' not found in WEB-INF/classes. Null URL received from system.");
        }
        return null;
    }
    try {
        File formsFile = new File(new URI(msgURL.toString()));
        InputStream stream = new FileInputStream(formsFile);
        return stream;
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (IOException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Configuration file 'messages.properties' not found in WEB-INF/classes.", e);
        }
    }
    return null;
}

From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java

private static boolean loadPropertiesFormsDefault() {
    // get the default file
    URL formsURL = AlfrescoController.class.getResource("/forms.properties");
    if (formsURL == null) {
        logger.error(//w  ww. j  av a 2  s. c o m
                "Configuration file 'forms.properties' not found in WEB-INF/classes. Null URL received from system.");
        return false;
    }
    try {
        File formsFile = new File(new URI(formsURL.toString()));
        InputStream stream = new FileInputStream(formsFile);
        return loadPropertiesFormsFromStream(stream);
    } catch (URISyntaxException e) {
        // I don't think this will ever be reached
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Configuration file 'forms.properties' not found in WEB-INF/classes.", e);
        }
    }
    return false;
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i(TAG, " ON ACTivyiy result");
    super.onActivityResult(requestCode, resultCode, data);
    Log.i("Result code ", " ^^ " + requestCode);
    if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
        Log.i(TAG, " ON ACTivyiy result ^^ 2");
        // Get the Uri of the selected file
        Uri uri = data.getData();/*from   w w  w. j  a v  a  2 s .  com*/
        Log.d("TAG", "File Uri: " + uri.toString());
        // Get the path
        String path;
        try {
            calcualteTodayDate();
            path = getPath(this, uri);
            documentFile = new File(path);

            String extension = "";
            int index = documentFile.getName().lastIndexOf(".");
            if (index != -1) {
                extension = documentFile.getName().substring(index + 1);
            }
            Bitmap bmImg = BitmapFactory.decodeFile(path);
            //   Bitmap resBm = getResizedBitmap(bmImg, 500);
            adapter.add(new StikyChat("", "<img", false, timeSend, "file" + path, 0, 0, "", "", "", null,
                    documentFile.getPath()));
            adapter.notifyDataSetChanged();
            lv.setSelection(adapter.getCount() - 1);
            Log.i("Document File ", " %%%% " + documentFile.getAbsolutePath());
            upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                    + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                    + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension
                    + "&type=file" + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                    + URLEncoder.encode(getResources().getString(R.string.url));
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    int serverResponseCode = uploadFile(documentFile);
                    if (serverResponseCode == 200) {
                        Log.i("Success", " is done! ");
                        flagChatting = false;
                        flagTransfer = true;
                        messageServer = "<img";
                        msg = "File transfer.";
                        recipientStkidGCM = recipientStkid;
                        new regTask().execute("GCM");
                        new regTask2().execute("Last Message!");
                    }
                }
            }).start();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (resultCode == Activity.RESULT_OK && requestCode == GALLERY_ACTIVITY_CODE) {
        Log.i(TAG, " Gallery is clicked..");
        calcualteTodayDate();
        imagePath = data.getStringExtra("picturePath");
        SDFile1 = new File(imagePath);

        String extension = "";
        int index = SDFile1.getName().lastIndexOf(".");
        if (index != -1) {
            extension = SDFile1.getName().substring(index + 1);
        }
        Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
        Bitmap resBm = getResizedBitmap(bmImg, 500);
        adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                SDFile1.getPath()));
        adapter.notifyDataSetChanged();
        lv.setSelection(adapter.getCount() - 1);
        Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
        upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                + URLEncoder.encode(getResources().getString(R.string.url));
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int serverResponseCode = uploadFile(SDFile1);
                if (serverResponseCode == 200) {
                    Log.i("Success", " is done! ");
                    flagChatting = false;
                    flagTransfer = true;
                    messageServer = "<img";
                    msg = "Image Transfer";
                    recipientStkidGCM = recipientStkid;
                    new regTask().execute("GCM");
                    new regTask2().execute("Last Message!");
                }
            }
        }).start();
        //performCrop(picturePath);
    } else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        convertImageUriToFile(imageUri, this);
        SDFile1 = new File(imagePath);

        String extension = "";
        int index = SDFile1.getName().lastIndexOf(".");
        if (index != -1) {
            extension = SDFile1.getName().substring(index + 1);
        }
        Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
        Bitmap resBm = getResizedBitmap(bmImg, 500);
        adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                SDFile1.getPath()));
        adapter.notifyDataSetChanged();
        lv.setSelection(adapter.getCount() - 1);
        Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
        upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                + URLEncoder.encode(getResources().getString(R.string.url));
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int serverResponseCode = uploadFile(SDFile1);
                if (serverResponseCode == 200) {
                    Log.i("Success", " is done! ");
                    flagChatting = false;
                    flagTransfer = true;
                    messageServer = "<img";
                    msg = "Image Transfer";
                    recipientStkidGCM = recipientStkid;
                    new regTask().execute("GCM");
                    new regTask2().execute("Last Message!");
                }
            }
        }).start();
    }
}

From source file:edu.jhu.pha.vospace.rest.TransfersController.java

/**
 * Submit the job to database/*w w  w .j a  v a  2  s. co  m*/
 * @param xmlNode the job XML document
 * @param username the username of the job owner
 * @return the job ID
 */
public static UUID submitJob(String xmlNode, String username) {
    StringReader strRead = new StringReader(xmlNode);
    UUID jobUID = UUID.randomUUID();
    try {

        JobDescription job = new JobDescription();
        job.setId(jobUID.toString());
        job.setUsername(username);
        job.setStartTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
        job.setState(JobDescription.STATE.PENDING);

        SAXBuilder xmlBuilder = new SAXBuilder();
        Element nodeElm = xmlBuilder.build(strRead).getRootElement();
        List<Element> paramNodes = nodeElm.getChildren();
        for (Iterator<Element> it = paramNodes.iterator(); it.hasNext();) {
            Element param = it.next();
            if (param.getName().equals("target")) {
                try {
                    job.setTarget(param.getValue());
                } catch (URISyntaxException e) {
                    logger.error("Error in job parse: " + e.getMessage());
                    throw new BadRequestException("InvalidURI");
                }
            } else if (param.getName().equals("direction")) {

                JobDescription.DIRECTION direct = JobDescription.DIRECTION.LOCAL;
                if (param.getValue().toUpperCase().endsWith("SPACE"))
                    direct = JobDescription.DIRECTION.valueOf(param.getValue().toUpperCase());

                job.setDirection(direct);

                if (direct == JobDescription.DIRECTION.PULLFROMVOSPACE) {
                    job.addProtocol(conf.getString("transfers.protocol.httpget"),
                            conf.getString("application.url") + "/data/" + job.getId());
                } else if (direct == JobDescription.DIRECTION.PUSHTOVOSPACE) {
                    job.addProtocol(conf.getString("transfers.protocol.httpput"),
                            conf.getString("application.url") + "/data/" + job.getId());
                } else if (direct == JobDescription.DIRECTION.LOCAL) {
                    try {
                        job.setDirectionTarget(param.getValue());
                    } catch (URISyntaxException e) {
                        logger.error("Error in job parse: " + e.getMessage());
                        throw new BadRequestException("InvalidURI");
                    }
                }
            } else if (param.getName().equals("view")) {
                job.addView(param.getValue());
            } else if (param.getName().equals("keepBytes")) {
                job.setKeepBytes(Boolean.parseBoolean(param.getValue()));
            } else if (param.getName().equals("protocol")) {
                String protocol = param.getAttributeValue("uri");
                String protocolEndpoint = param.getChildText("protocolEndpoint",
                        Namespace.getNamespace(VOS_NAMESPACE));

                if (job.getDirection().equals(DIRECTION.PULLFROMVOSPACE)
                        || job.getDirection().equals(DIRECTION.PUSHTOVOSPACE)) {
                    protocolEndpoint = conf.getString("application.url") + "/data/" + job.getId();
                }

                if (null != protocol && null != protocolEndpoint)
                    job.addProtocol(protocol, protocolEndpoint);
                else
                    throw new BadRequestException("InvalidArgument");
            }
        }

        JobsProcessor.getDefaultImpl().submitJob(username, job);
    } catch (JDOMException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    } catch (IOException e) {
        logger.error(e);
        throw new InternalServerErrorException(e);
    } catch (IllegalArgumentException e) {
        logger.error("Error calling the job task: " + e.getMessage());
        throw new InternalServerErrorException("InternalFault");
    } finally {
        strRead.close();
    }
    return jobUID;
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Displays a dialog which will provide options for selecting a configuration
 *///from w w  w . ja  v a2  s . c  om
private void showReceiverConfigurationPanel() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            final JDialog dialog = new JDialog(LogUI.this, true);
            dialog.setTitle("Load events into Chainsaw");
            dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

            dialog.setResizable(false);

            receiverConfigurationPanel.setCompletionActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dialog.setVisible(false);

                    if (receiverConfigurationPanel.getModel().isCancelled()) {
                        return;
                    }
                    applicationPreferenceModel
                            .setShowNoReceiverWarning(!receiverConfigurationPanel.isDontWarnMeAgain());
                    //remove existing plugins
                    List plugins = pluginRegistry.getPlugins();
                    for (Iterator iter = plugins.iterator(); iter.hasNext();) {
                        Plugin plugin = (Plugin) iter.next();
                        //don't stop ZeroConfPlugin if it is registered
                        if (!plugin.getName().toLowerCase(Locale.ENGLISH).contains("zeroconf")) {
                            pluginRegistry.stopPlugin(plugin.getName());
                        }
                    }
                    URL configURL = null;

                    if (receiverConfigurationPanel.getModel().isNetworkReceiverMode()) {
                        int port = receiverConfigurationPanel.getModel().getNetworkReceiverPort();

                        try {
                            Class receiverClass = receiverConfigurationPanel.getModel()
                                    .getNetworkReceiverClass();
                            Receiver networkReceiver = (Receiver) receiverClass.newInstance();
                            networkReceiver.setName(receiverClass.getSimpleName() + "-" + port);

                            Method portMethod = networkReceiver.getClass().getMethod("setPort",
                                    new Class[] { int.class });
                            portMethod.invoke(networkReceiver, new Object[] { new Integer(port) });

                            networkReceiver.setThreshold(Level.TRACE);

                            pluginRegistry.addPlugin(networkReceiver);
                            networkReceiver.activateOptions();
                            receiversPanel.updateReceiverTreeInDispatchThread();
                        } catch (Exception e3) {
                            MessageCenter.getInstance().getLogger().error("Error creating Receiver", e3);
                            MessageCenter.getInstance().getLogger()
                                    .info("An error occurred creating your Receiver");
                        }
                    } else if (receiverConfigurationPanel.getModel().isLog4jConfig()) {
                        File log4jConfigFile = receiverConfigurationPanel.getModel().getLog4jConfigFile();
                        if (log4jConfigFile != null) {
                            try {
                                Map entries = LogFilePatternLayoutBuilder
                                        .getAppenderConfiguration(log4jConfigFile);
                                for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) {
                                    try {
                                        Map.Entry entry = (Map.Entry) iter.next();
                                        String name = (String) entry.getKey();
                                        Map values = (Map) entry.getValue();
                                        //values: conversion, file
                                        String conversionPattern = values.get("conversion").toString();
                                        File file = new File(values.get("file").toString());
                                        URL fileURL = file.toURI().toURL();
                                        String timestampFormat = LogFilePatternLayoutBuilder
                                                .getTimeStampFormat(conversionPattern);
                                        String receiverPattern = LogFilePatternLayoutBuilder
                                                .getLogFormatFromPatternLayout(conversionPattern);
                                        VFSLogFilePatternReceiver fileReceiver = new VFSLogFilePatternReceiver();
                                        fileReceiver.setName(name);
                                        fileReceiver.setAutoReconnect(true);
                                        fileReceiver.setContainer(LogUI.this);
                                        fileReceiver.setAppendNonMatches(true);
                                        fileReceiver.setFileURL(fileURL.toURI().toString());
                                        fileReceiver.setTailing(true);
                                        fileReceiver.setLogFormat(receiverPattern);
                                        fileReceiver.setTimestampFormat(timestampFormat);
                                        fileReceiver.setThreshold(Level.TRACE);
                                        pluginRegistry.addPlugin(fileReceiver);
                                        fileReceiver.activateOptions();
                                        receiversPanel.updateReceiverTreeInDispatchThread();
                                    } catch (URISyntaxException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    } else if (receiverConfigurationPanel.getModel().isLoadConfig()) {
                        configURL = receiverConfigurationPanel.getModel().getConfigToLoad();
                    } else if (receiverConfigurationPanel.getModel().isLogFileReceiverConfig()) {
                        try {
                            URL fileURL = receiverConfigurationPanel.getModel().getLogFileURL();
                            if (fileURL != null) {
                                VFSLogFilePatternReceiver fileReceiver = new VFSLogFilePatternReceiver();
                                fileReceiver.setName(fileURL.getFile());
                                fileReceiver.setAutoReconnect(true);
                                fileReceiver.setContainer(LogUI.this);
                                fileReceiver.setAppendNonMatches(true);
                                fileReceiver.setFileURL(fileURL.toURI().toString());
                                fileReceiver.setTailing(true);
                                if (receiverConfigurationPanel.getModel().isPatternLayoutLogFormat()) {
                                    fileReceiver.setLogFormat(
                                            LogFilePatternLayoutBuilder.getLogFormatFromPatternLayout(
                                                    receiverConfigurationPanel.getModel().getLogFormat()));
                                } else {
                                    fileReceiver
                                            .setLogFormat(receiverConfigurationPanel.getModel().getLogFormat());
                                }
                                fileReceiver.setTimestampFormat(
                                        receiverConfigurationPanel.getModel().getLogFormatTimestampFormat());
                                fileReceiver.setThreshold(Level.TRACE);

                                pluginRegistry.addPlugin(fileReceiver);
                                fileReceiver.activateOptions();
                                receiversPanel.updateReceiverTreeInDispatchThread();
                            }
                        } catch (Exception e2) {
                            MessageCenter.getInstance().getLogger().error("Error creating Receiver", e2);
                            MessageCenter.getInstance().getLogger()
                                    .info("An error occurred creating your Receiver");
                        }
                    }
                    if (configURL == null && receiverConfigurationPanel.isDontWarnMeAgain()) {
                        //use the saved config file as the config URL if defined
                        if (receiverConfigurationPanel.getModel().getSaveConfigFile() != null) {
                            try {
                                configURL = receiverConfigurationPanel.getModel().getSaveConfigFile().toURI()
                                        .toURL();
                            } catch (MalformedURLException e1) {
                                e1.printStackTrace();
                            }
                        } else {
                            //no saved config defined but don't warn me is checked - use default config
                            configURL = receiverConfigurationPanel.getModel().getDefaultConfigFileURL();
                        }
                    }
                    if (configURL != null) {
                        MessageCenter.getInstance().getLogger()
                                .debug("Initialiazing Log4j with " + configURL.toExternalForm());
                        final URL finalURL = configURL;
                        new Thread(new Runnable() {
                            public void run() {
                                if (receiverConfigurationPanel.isDontWarnMeAgain()) {
                                    applicationPreferenceModel.setConfigurationURL(finalURL.toExternalForm());
                                } else {
                                    try {
                                        if (new File(finalURL.toURI()).exists()) {
                                            loadConfigurationUsingPluginClassLoader(finalURL);
                                        }
                                    } catch (URISyntaxException e) {
                                        //ignore
                                    }
                                }

                                receiversPanel.updateReceiverTreeInDispatchThread();
                            }
                        }).start();
                    }
                    File saveConfigFile = receiverConfigurationPanel.getModel().getSaveConfigFile();
                    if (saveConfigFile != null) {
                        ReceiversHelper.getInstance().saveReceiverConfiguration(saveConfigFile);
                    }
                }
            });

            receiverConfigurationPanel.setDialog(dialog);
            dialog.getContentPane().add(receiverConfigurationPanel);

            dialog.pack();

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            dialog.setLocation((screenSize.width / 2) - (dialog.getWidth() / 2),
                    (screenSize.height / 2) - (dialog.getHeight() / 2));

            dialog.setVisible(true);
        }
    });
}

From source file:org.LexGrid.LexBIG.gui.ValueSetDefinitionDetails.java

private void setUpVSDButtonsGp() {
    GridData gd = new GridData(GridData.FILL, GridData.CENTER, true, true);
    gd.horizontalIndent = 5;//w w w.ja va  2  s.c o m

    buttonsGp_ = new Group(valueSetsComposite_, SWT.NONE);
    buttonsGp_.setLayoutData(gd);

    GridLayout layout = new GridLayout(1, false);
    buttonsGp_.setLayout(layout);

    // edit button
    editButton_ = Utility.makeButton("Edit", buttonsGp_,
            GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_CENTER);
    editButton_.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {
            // check that edit is being done only on current revision
            // checkrevision();

            //                contextCombo_.redraw();
            //                sourceCombo_.redraw();
            enableTextFields();
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            // 
        }

    });

    resolveButton_ = Utility.makeButton("Resolve", buttonsGp_,
            GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
    resolveButton_.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {

            if (vd_ != null)
                new ValueSetDefResolveCSFilter(lb_vsd_gui_, vd_, shell_, true, false);
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            // 
        }

    });

    removeButton_ = Utility.makeButton("Remove", buttonsGp_,
            GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
    removeButton_.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {
            try {
                // check if the selected revision is current.
                // checkRevision();
                URI uri = null;
                try {
                    if (vd_ != null)
                        uri = new URI(vd_.getValueSetDefinitionURI());
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (uri == null) {
                    errorHandler.showError("No value set definition selected",
                            "You must select a value set definition first.");
                    return;
                }

                MessageBox messageBox = new MessageBox(shell_, SWT.ICON_QUESTION | SWT.YES | SWT.NO);
                messageBox.setText("Remove value set definition?");
                messageBox.setMessage("Do you really want to remove the selected value set definition?");
                if (messageBox.open() == SWT.YES) {
                    lb_vsd_gui_.getValueSetDefinitionService().removeValueSetDefinition(uri);
                    lb_vsd_gui_.refreshValueSetDefList();

                    errorHandler.showInfo("Removed", "Selected Value Set Definition has been removed");
                    shell_.dispose();
                }
            } catch (LBException e) {
                errorHandler.showError("Error executing remove", e.getMessage());
            }
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            //
        }

    });

    saveButton_ = Utility.makeButton("Save", buttonsGp_,
            GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
    saveButton_.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {
            if (StringUtils.isEmpty(vsdURITxt_.getText())) {
                errorHandler.showError("Invalid Data", "Value Set Definition URI can not be empty");
                vsdURITxt_.setFocus();
            } else {
                try {
                    new URI(vsdURITxt_.getText());
                } catch (URISyntaxException e) {
                    errorHandler.showError("Invalid Data", "Value Set Definition URI is NOT WELL FORMED");
                    vsdURITxt_.setFocus();
                    return;
                }

                boolean allDatesGood = true;
                if (StringUtils.isNotEmpty(effDateTxt_.getText())) {
                    if (!isDateValid(effDateTxt_.getText())) {
                        allDatesGood = false;
                        errorHandler.showError("Invalid Data", "The date provided is in an invalid date or "
                                + " format. Please enter date in MM/dd/YYYY format.");
                        effDateTxt_.setBackground(redColor_);
                        effDateTxt_.setFocus();
                    }
                }
                if (StringUtils.isNotEmpty(expDateTxt_.getText())) {
                    if (!isDateValid(expDateTxt_.getText())) {
                        allDatesGood = false;
                        errorHandler.showError("Invalid Data", "The date provided is in an invalid date or "
                                + " format. Please enter date in MM/dd/YYYY format.");
                        expDateTxt_.setBackground(redColor_);
                        expDateTxt_.setFocus();
                    }
                }

                if (allDatesGood) {
                    buildAndLoadVSD();

                    if (changesSaved) {
                        errorHandler.showInfo("Changes Saved", "Changes to Value Set Definition Saved");
                        enablePropertyButtons();
                        enableRefButtons();
                        refreshSupportedAttribList();
                        refreshDefinitionEntryList();
                        refreshVSDPropertyList();
                        setChangesMade(false);
                        lb_vsd_gui_.refreshValueSetDefList();
                        resolveButton_.setEnabled(true);
                        changesSaved = false;
                    }
                }
            }

        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            //
        }

    });

    closeButton_ = Utility.makeButton("Close", buttonsGp_,
            GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
    closeButton_.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {
            if (!isChangesMade()) {
                shell_.dispose();
            } else {
                MessageBox messageBox = new MessageBox(shell_, SWT.ICON_QUESTION | SWT.YES | SWT.NO);
                messageBox.setText("Changes have been made?");
                messageBox.setMessage("Changes have been made. Ignore them?");
                if (messageBox.open() == SWT.YES) {
                    shell_.dispose();
                }
            }
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            //
        }

    });
}

From source file:com.akop.bach.parser.XboxLiveParser.java

private GameOverviewInfo parseGameOverview(String url) throws IOException, ParserException {
    String loadUrl = url;/*from w  ww.ja  v  a 2  s  . com*/

    if (PATTERN_GAME_OVERVIEW_REDIRECTING_URL.matcher(url).find()) {
        // Redirecting URL; figure out where it's redirecting

        HttpParams p = mHttpClient.getParams();

        try {
            p.setParameter("http.protocol.max-redirects", 1);

            HttpGet httpget = new HttpGet(url);
            HttpContext context = new BasicHttpContext();
            HttpResponse response = mHttpClient.execute(httpget, context);

            HttpEntity entity = response.getEntity();
            if (entity != null)
                entity.consumeContent();

            HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

            try {
                loadUrl = new URI(url).resolve(request.getURI()).toString();
            } catch (URISyntaxException e) {
                if (App.getConfig().logToConsole())
                    e.printStackTrace();
            }

            if (App.getConfig().logToConsole())
                App.logv("Redirection URL determined to be " + loadUrl);
        } finally {
            p.setParameter("http.protocol.max-redirects", 0);
        }
    }

    String page = getResponse(loadUrl.concat("?NoSplash=1"));

    GameOverviewInfo overview = new GameOverviewInfo();

    Matcher m;
    if (!(m = PATTERN_GAME_OVERVIEW_TITLE.matcher(page)).find())
        throw new ParserException(mContext, R.string.error_no_details_available);

    overview.Title = htmlDecode(m.group(1));
    if ((m = PATTERN_GAME_OVERVIEW_DESCRIPTION.matcher(page)).find())
        overview.Description = htmlDecode(m.group(1));

    if ((m = PATTERN_GAME_OVERVIEW_MANUAL.matcher(page)).find())
        overview.ManualUrl = m.group(1);

    if ((m = PATTERN_GAME_OVERVIEW_ESRB.matcher(page)).find()) {
        overview.EsrbRatingDescription = htmlDecode(m.group(1));
        overview.EsrbRatingIconUrl = m.group(2);
    }

    if ((m = PATTERN_GAME_OVERVIEW_BANNER.matcher(page)).find())
        overview.BannerUrl = m.group(1);

    m = PATTERN_GAME_OVERVIEW_IMAGE.matcher(page);
    while (m.find())
        overview.Screenshots.add(m.group(1));

    return overview;
}

From source file:org.mumod.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;//from ww  w .j a va2  s.c om

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}