Example usage for java.net URISyntaxException getMessage

List of usage examples for java.net URISyntaxException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns a string describing the parse error.

Usage

From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java

/** Called when the activity is first created. */
@Override/*from  w w  w . jav a2  s.com*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        SocketImplHookFactory.initialize();
    }
    {
        ProxySelector proxySelector = ProxySelector.getDefault();
        Log.d(TAG, "proxySelector=" + proxySelector);
        if (null != proxySelector) {
            URI uri = null;
            try {
                uri = new URI("http://www.google.com/");
            } catch (URISyntaxException e) {
                Log.d(TAG, e.toString());
            }
            List<Proxy> proxies = proxySelector.select(uri);
            if (null != proxies) {
                for (final Proxy proxy : proxies) {
                    Log.d(TAG, " proxy=" + proxy);
                }
            }
        }
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:au.org.ala.delta.intkey.Intkey.java

/**
 * This method saves information about the currently opened dataset:<br/>
 * 1. If the dataset was downloaded from a remote location, the user will be
 * given the option to save it to disk<br/>
 * 2. The dataset is added to the list of most recently used datasets<br/>
 * 3. If the dataset is not currently saved in the dataset index, the user
 * will be given the option to do this./*from w  w w  . jav a  2  s.  co m*/
 */
private void saveCurrentlyOpenedDataset() {
    String datasetTitle = _context.getDataset().getHeadingWithoutFormatting();

    // if the dataset was downloaded, ask the user if they wish to save it
    StartupFileData startupFileData = _context.getStartupFileData();

    boolean remoteDatasetSavedLocally = false;

    // Always use the path to the startup file supplied to the NEWDATASET
    // directive
    // Ignore the "inkFile" URL listed in the startup file.
    String datasetPath;
    URL startupFileURL = _context.getDatasetStartupURL();
    if (startupFileURL.getProtocol().equalsIgnoreCase("file")) {
        try {
            datasetPath = new File(startupFileURL.toURI()).getAbsolutePath();
        } catch (URISyntaxException ex) {
            datasetPath = startupFileURL.toString();
        }
    } else {
        datasetPath = startupFileURL.toString();
    }

    if (startupFileData != null && startupFileData.isRemoteDataset()) {
        int chosenOption = JOptionPane.showConfirmDialog(getMainFrame(),
                UIUtils.getResourceString("SaveDownloadedDatasetPrompt.caption", datasetTitle),
                UIUtils.getResourceString("Save.caption"), JOptionPane.YES_NO_OPTION);
        if (chosenOption == JOptionPane.YES_OPTION) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            int returnVal = fileChooser.showOpenDialog(getMainFrame());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File saveDir = fileChooser.getSelectedFile();

                try {
                    File newInkFile = StartupUtils.saveRemoteDataset(_context, saveDir);
                    datasetPath = newInkFile.getAbsolutePath();
                    remoteDatasetSavedLocally = true;

                    // Remove the current startup file from the MRU as a new
                    // file will go in its
                    // place.
                    UIUtils.removeFileFromMRU(_context.getDatasetStartupFile().getAbsolutePath());
                } catch (IOException ex) {
                    Logger.error("Error saving downloaded dataset", ex);
                    displayErrorMessage(
                            UIUtils.getResourceString("ErrorSavingDownloadedDataset.error", ex.getMessage()));
                    // not much we can do here, just abort saving/adding to
                    // recents list.
                    return;
                }
            }
        }
    }

    // Add to list of most recently used datasets.
    if (_context.getDataset() != null) {
        UIUtils.addFileToMRU(datasetPath, datasetTitle, UIUtils.getPreviouslyUsedFiles());
    }

    // If the dataset is not present in the dataset index, give the user the
    // option to add it
    String promptMessage = null;
    if (startupFileData != null && startupFileData.isRemoteDataset()) {
        if (remoteDatasetSavedLocally) {
            promptMessage = UIUtils.getResourceString("AddSavedCopyOfDatasetToIndexPrompt.caption",
                    datasetTitle);
        } else {
            promptMessage = UIUtils.getResourceString("AddStartupFileForRemoteDatasetToIndexPrompt.caption",
                    datasetTitle);
        }
    } else {
        promptMessage = UIUtils.getResourceString("AddDatasetToIndexPrompt.caption", datasetTitle);
    }

    // check if the datasetPath is already present in the index
    if (!UIUtils.getDatasetIndexAsMap().containsKey(datasetPath)) {
        int chosenOption = JOptionPane.showConfirmDialog(getMainFrame(), promptMessage,
                UIUtils.getResourceString("AddToDataset.caption"), JOptionPane.YES_NO_OPTION);
        if (chosenOption == JOptionPane.YES_OPTION) {
            addToDatasetIndex(datasetTitle, datasetPath);
        }
    }
}

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 a va  2s . co  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:org.witness.ssc.xfer.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.
    ((SSCXferActivity) activity).startedUploading();
    final Resources res = activity.getResources();

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

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();

            if (useProxy) {
                HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }//w w  w.ja  v a2  s. c  o m

            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;
            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.
                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {
                        int lastPercent = 0;

                        @Override
                        public void transferred(long num) {

                            percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f);
                            //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength);
                            if (lastPercent != percentUploaded) {
                                ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded);
                                lastPercent = percentUploaded;
                            }
                        }

                    });

            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);

            totalLength = entity.getContentLength();

            // 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();

            if (failed) {
                // 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.

                        ((SSCXferActivity) activity).finishedUploading(false);

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

                return;
            }

            Log.d(TAG, " video bin got back " + response);

            // 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, "");

            // 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.

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

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.WebcrawlerConnector.java

/** Convert an absolute or relative URL to a document identifier.  This may involve several steps at some point,
* but right now it does NOT involve converting the host name to a canonical host name.
* (Doing so would destroy the ability of virtually hosted sites to do the right thing,
* since the original host name would be lost.)  Thus, we do the conversion to IP address
* right before we actually fetch the document.
*@param parentIdentifier the identifier of the document in which the raw url was found, or null if none.
*@param rawURL the starting, un-normalized, un-canonicalized URL.
*@param filter the filter object, used to remove unmatching URLs.
*@return the canonical URL (the document identifier), or null if the url was illegal.
*//*from  w  ww .  j  ava2  s . c  o  m*/
protected String makeDocumentIdentifier(String parentIdentifier, String rawURL, DocumentURLFilter filter)
        throws ManifoldCFException {
    try {
        WebURL url;
        if (parentIdentifier != null) {
            WebURL parentURL = new WebURL(parentIdentifier);
            url = parentURL.resolve(rawURL);
        } else
            url = new WebURL(rawURL);

        String protocol = url.getScheme();
        String host = url.getHost();

        // The new URL better darn well have a host and a protocol, and we only know how to deal with
        // http and https.
        if (protocol == null || host == null) {
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors
                        .debug("WEB: Can't use url '" + rawURL + "' because it has no protocol or host");
            return null;
        }
        if (!understoodProtocols.contains(protocol)) {
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors.debug("WEB: Can't use url '" + rawURL
                        + "' because it has an unsupported protocol '" + protocol + "'");
            return null;
        }
        if (!filter.isHostLegal(host)) {
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors.debug("WEB: Can't use url '" + rawURL
                        + "' because its host is not found in the seeds ('" + host + "')");
            return null;
        }

        // Canonicalization procedure.
        // The query part of the URL may contain bad parameters (session id's, for instance), or may be ordered in such a
        // way as to prevent an effectively identical URL from being matched.  The anchor part of the URL should also be stripped.
        // This code performs both of these activities in a simple way; rewrites of various pieces may get more involved if we add
        // the ability to perform mappings using criteria specified in the UI.  Right now we don't.
        String id = doCanonicalization(filter, url);
        if (id == null)
            return null;

        // As a last basic legality check, go through looking for illegal characters.
        int i = 0;
        while (i < id.length()) {
            char x = id.charAt(i++);
            // Only 7-bit ascii is allowed in URLs - and that has limits too (no control characters)
            if (x < ' ' || x > 127) {
                if (Logging.connectors.isDebugEnabled())
                    Logging.connectors.debug(
                            "WEB: Can't use url '" + rawURL + "' because it has illegal characters in it");
                return null;
            }
        }

        // Check to be sure the canonicalized URL is in fact one of the ones we want to include
        if (!filter.isDocumentLegal(id))
            return null;

        return id;
    } catch (java.net.URISyntaxException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors
                    .debug("WEB: Can't use url '" + rawURL + "' because it is badly formed: " + e.getMessage());
        return null;
    } catch (java.lang.IllegalArgumentException e) {
        return null;
    } catch (java.lang.NullPointerException e) {
        // This gets tossed by url.toAsciiString() for reasons I don't understand, but which have to do with a malformed URL.
        return null;
    }
}

From source file:com.vmware.identity.idm.server.IdentityManager.java

/**
 * Checks the connectivity to an identity provider
 *
 * @param tenantName  Name of tenant, non-null non-empty, required
 * @param providerUri Location of identity provider. non-null non-empty, required
 * @param authType    Type of authentication. required.
 *                 currently supports AuthenticationType.PASSWORD only.
 * @param userName    Login identifier. non-null, required
 * @param pwd         Password    non-null non-empty, required
 * @param certs       Trusted certificates used for SSL connection
 * @throws InvalidPrincipalException    user name is invalid (empty)
 * @throws IDMLoginException. If one or more of the input argument is illegal.
 *                                 Or URI syntax is incorrect.
 * @throws IDMException//  w ww .j a  v a  2 s .  c  o  m
 * @see AuthenticationType
 */
private void probeProviderConnectivity(String tenantName, String providerUri, AuthenticationType authType,
        String userName, String pwd, LdapCertificateValidationSettings certValidationSettings)
        throws Exception {

    URI uri = null;
    try {
        ValidateUtil.validateNotEmpty(tenantName, "tenantName");
        ValidateUtil.validateNotEmpty(providerUri, "providerUri");

        // providerUri for now has to start with ldap||ldaps
        try {
            uri = new URI(providerUri);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e.getMessage());
        }

        if ((!uri.getScheme().toLowerCase().equals("ldap"))
                && (!uri.getScheme().toLowerCase().equals("ldaps"))) {
            throw new IllegalArgumentException(String.format("Unsupported providerUri='%s'.", providerUri));
        }

        if (AuthenticationType.PASSWORD != authType) {
            throw new IllegalArgumentException(
                    String.format("AuthenticationType='%s' is not supported.", authType.toString()));
        }
        ServerUtils.validateNotEmptyUsername(userName);
        ValidateUtil.validateNotNull(pwd, "pwd");
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw ex;
    } //Validation done.

    try {
        Collection<URI> uris = Collections.unmodifiableList(Arrays.asList(new URI(providerUri)));
        // connection must be closed if succeeded ....
        try (ILdapConnectionEx connection = ServerUtils.getLdapConnectionByURIs(uris, userName, pwd,
                AuthenticationType.PASSWORD, false, certValidationSettings)) {
        }
        return;
    } catch (Exception ex) {
        String msg = String.format(
                "Failed to probe provider connectivity [URI: %s]; tenantName [%s], userName [%s]", providerUri,
                tenantName, userName);

        logger.warn(msg);

        throw new IDMLoginException(msg, uri, ex);
    }
}

From source file:com.vmware.identity.idm.server.IdentityManager.java

private void probeProviderConnectivity(String tenantName, IIdentityStoreData idsData) throws Exception {

    ValidateUtil.validateNotNull(idsData.getExtendedIdentityStoreData(), "idsData details");
    if (AuthenticationType.PASSWORD != idsData.getExtendedIdentityStoreData().getAuthenticationType()) {
        throw new IllegalArgumentException(String.format("AuthenticationType='%s' is not supported.",
                idsData.getExtendedIdentityStoreData().getAuthenticationType().toString()));
    }/*from   w ww. j a  v a2 s . c o  m*/
    ServerUtils.validateNotEmptyUsername(idsData.getExtendedIdentityStoreData().getUserName());
    ValidateUtil.validateNotNull(idsData.getExtendedIdentityStoreData().getPassword(), "pwd");

    IIdentityProvider provider = providerFactory.buildProvider(tenantName, idsData,
            idsData.getExtendedIdentityStoreData().getCertificates());
    if (!(provider instanceof BaseLdapProvider))
        throw new IllegalArgumentException(
                String.format("Supported provider type is %s, %s provider is not of supported type.",
                        BaseLdapProvider.class.toString(), provider.getClass().toString()));

    StringBuilder connections = new StringBuilder();
    for (String connectionStr : idsData.getExtendedIdentityStoreData().getConnectionStrings()) {
        ValidateUtil.validateNotEmpty(connectionStr, "connectionString");

        try {
            URI connectionUri = new URI(connectionStr);
            DirectoryStoreProtocol protocol = DirectoryStoreProtocol
                    .getValue(connectionUri.getScheme().toString());
            if (protocol == null) {
                throw new IllegalArgumentException(
                        String.format("Unsupported providerUri='%s'.", connectionUri));
            } else if (protocol == DirectoryStoreProtocol.LDAPS) {
                ValidateUtil.validateNotEmpty(idsData.getExtendedIdentityStoreData().getCertificates(),
                        "IdentityStore certificates");
                for (X509Certificate cert : idsData.getExtendedIdentityStoreData().getCertificates()) {
                    ValidateUtil.validateCertificate(cert);
                }
            }
            connections.append(connectionStr + " ");
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
    }

    try {
        //probe connectivity and DN check
        ((BaseLdapProvider) provider).probeConnectionSettings();
    } catch (Exception ex) {
        String msg = String.format(
                "Failed to probe provider connectivity [URI: %s]; tenantName [%s], userName [%s]",
                connections.toString(), tenantName, idsData.getExtendedIdentityStoreData().getUserName());

        logger.warn(msg);

        throw new IDMLoginException(msg, null, ex);
    }
}

From source file:bammerbom.ultimatecore.spongeapi.commands.CmdPlugin.java

@Override
public void run(final CommandSender cs, String label, final String[] args) {
    //help/*from  w w  w  .j a v a 2 s . c  o  m*/
    if (!r.checkArgs(args, 0) || args[0].equalsIgnoreCase("help")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.help", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        cs.sendMessage(TextColors.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(TextColors.GOLD + "================================");
    } //load
    else if (args[0].equalsIgnoreCase("load")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.load", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpLoad");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile(),
                args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
            return;
        }
        if (!f.canRead()) {
            r.sendMes(cs, "pluginFileNoReadAcces");
            return;
        }
        Plugin p;
        try {
            p = pm.loadPlugin(f);
            if (p == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependency", "%Message",
                    ex.getMessage() != null ? ex.getMessage() : "");
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginLoadSucces");
        } else {
            r.sendMes(cs, "pluginLoadFailed");
        }
    } //unload
    else if (args[0].equalsIgnoreCase("unload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.unload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUnload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(TextColors.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependent", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        r.sendMes(cs, "pluginUnloadUnloading");
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        r.sendMes(cs, "pluginUnloadUnloaded");
    } //enable
    else if (args[0].equalsIgnoreCase("enable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.enable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpEnable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginAlreadyEnabled");
            return;
        }
        pm.enablePlugin(p);
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginEnableSucces");
        } else {
            r.sendMes(cs, "pluginEnableFail");
        }
    } //disable
    else if (args[0].equalsIgnoreCase("disable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.disable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDisable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(TextColors.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependent", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        pm.disablePlugin(p);
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginDisableSucces");
        } else {
            r.sendMes(cs, "pluginDisableFailed");
        }
    } //reload
    else if (args[0].equalsIgnoreCase("reload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpReload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        pm.disablePlugin(p);
        pm.enablePlugin(p);
        r.sendMes(cs, "pluginReloadMessage");
    } //reloadall
    else if (args[0].equalsIgnoreCase("reloadall")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reloadall", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        for (Plugin p : pm.getPlugins()) {
            pm.disablePlugin(p);
            pm.enablePlugin(p);
        }
        r.sendMes(cs, "pluginReloadallMessage");
    } //delete
    else if (args[0].equalsIgnoreCase("delete")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.delete", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDelete");
            return;
        }
        String del = args[1];
        if (!del.endsWith(".jar")) {
            del = del + ".jar";
        }
        if (del.contains(File.separator)) {
            r.sendMes(cs, "pluginDeleteDontLeavePluginFolder");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile() + File.separator + del);
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", del);
            return;
        }
        if (f.delete()) {
            r.sendMes(cs, "pluginDeleteSucces");
        } else {
            r.sendMes(cs, "pluginDeleteFailed");
        }
    } //commands
    else if (args[0].equalsIgnoreCase("commands")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.commands", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpCommands");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        Map<String, Map<String, Object>> cmds = p.getDescription().getCommands();
        if (cmds == null) {
            r.sendMes(cs, "pluginCommandsNoneRegistered");
            return;
        }
        String command = "plugin " + p.getName();
        String pageStr = args.length > 2 ? args[2] : null;
        UText input = new TextInput(cs);
        UText output;
        if (input.getLines().isEmpty()) {
            if ((r.isInt(pageStr)) || (pageStr == null)) {
                output = new PluginCommandsInput(cs, args[1].toLowerCase());
            } else {
                r.sendMes(cs, "pluginCommandsPageNotNumber");
                return;
            }
        } else {
            output = input;
        }
        TextPager pager = new TextPager(output);
        pager.showPage(pageStr, null, command, cs);
    } //update
    else if (args[0].equalsIgnoreCase("update")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.update", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdate");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        URL u = Bukkit.getPluginManager().getPlugin("UltimateCore").getClass().getProtectionDomain()
                .getCodeSource().getLocation();
        File f;
        try {
            f = new File(u.toURI());
        } catch (URISyntaxException e) {
            f = new File(u.getPath());
        }
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        try {
            Plugin p2 = pm.loadPlugin(f);
            if (p2 == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p2);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependendy", "%Message", ex.getMessage());
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
    } //list
    else if (args[0].equalsIgnoreCase("list")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.list", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        r.sendMes(cs, "pluginsList", "%Plugins", PluginUtil.getPluginList());
    } //info
    else if (args[0].equalsIgnoreCase("info")) {
        if (!r.perm(cs, "uc.plugin.info", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpInfo");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        PluginDescriptionFile pdf = p.getDescription();
        if (pdf == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        String version = pdf.getVersion();
        List<String> authors = pdf.getAuthors();
        String site = pdf.getWebsite();
        List<String> softDep = pdf.getSoftDepend();
        List<String> dep = pdf.getDepend();
        String name = pdf.getName();
        String desc = pdf.getDescription();
        if (name != null && !name.isEmpty()) {
            r.sendMes(cs, "pluginInfoName", "%Name", name);
        }
        if (version != null && !version.isEmpty()) {
            r.sendMes(cs, "pluginInfoVersion", "%Version", version);
        }
        if (site != null && !site.isEmpty()) {
            r.sendMes(cs, "pluginInfoWebsite", "%Website", site);
        }
        if (desc != null && !desc.isEmpty()) {
            r.sendMes(cs, "pluginInfoDescription", "%Description", desc.replaceAll("\r?\n", ""));
        }
        if (authors != null && !authors.isEmpty()) {
            r.sendMes(cs, "pluginInfoAuthor", "%S", ((authors.size() > 1) ? "s" : ""), "%Author",
                    StringUtil.join(TextColors.RESET + ", " + r.neutral, authors));
        }
        if (softDep != null && !softDep.isEmpty()) {
            r.sendMes(cs, "pluginInfoSoftdeps", "%Softdeps",
                    StringUtil.join(TextColors.RESET + ", " + r.neutral, softDep));
        }
        if (dep != null && !dep.isEmpty()) {
            r.sendMes(cs, "pluginInfoDeps", "%Deps", StringUtil.join(TextColors.RESET + ", " + r.neutral, dep));
        }
        r.sendMes(cs, "pluginInfoEnabled", "%Enabled", ((p.isEnabled()) ? r.mes("yes") : r.mes("no")));
    } //updatecheck
    else if (args[0].equalsIgnoreCase("updatecheck")) {
        if (!r.perm(cs, "uc.plugin.updatecheck", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdatecheck");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        final String tag;
        try {
            tag = URLEncoder.encode(r.checkArgs(args, 2) ? args[2] : p.getName(), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        if (p.getDescription() == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        final String v = p.getDescription().getVersion() == null ? r.mes("pluginNotSet")
                : p.getDescription().getVersion();
        Runnable ru = new Runnable() {
            @Override
            public void run() {
                try {
                    String n = "";
                    String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + tag + "/files.rss";
                    URL url = new URL(pluginUrlString);
                    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    NodeList nodes = doc.getElementsByTagName("item");
                    Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        Element firstElement = (Element) firstNode;
                        NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                        Element firstNameElement = (Element) firstElementTagName.item(0);
                        NodeList firstNodes = firstNameElement.getChildNodes();
                        n = firstNodes.item(0).getNodeValue();
                    }

                    r.sendMes(cs, "pluginUpdatecheckCurrent", "%Current", v + "");
                    r.sendMes(cs, "pluginUpdatecheckNew", "%New", n + "");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    r.sendMes(cs, "pluginUpdatecheckFailed");
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } //updatecheckall
    else if (args[0].equalsIgnoreCase("updatecheckall")) {
        if (!r.perm(cs, "uc.plugin.updatecheckall", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (Plugin p : pm.getPlugins()) {
                    if (p.getDescription() == null) {
                        continue;
                    }
                    String version = p.getDescription().getVersion();
                    if (version == null) {
                        continue;
                    }
                    String n = "";
                    try {
                        String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/"
                                + p.getName().toLowerCase() + "/files.rss";
                        URL url = new URL(pluginUrlString);
                        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(url.openConnection().getInputStream());
                        doc.getDocumentElement().normalize();
                        NodeList nodes = doc.getElementsByTagName("item");
                        Node firstNode = nodes.item(0);
                        if (firstNode.getNodeType() == 1) {
                            Element firstElement = (Element) firstNode;
                            NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                            Element firstNameElement = (Element) firstElementTagName.item(0);
                            NodeList firstNodes = firstNameElement.getChildNodes();
                            n = firstNodes.item(0).getNodeValue();
                            a++;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                    if (n.contains(version)) {
                        continue;
                    }
                    r.sendMes(cs, "pluginUpdatecheckallAvailable", "%Old", version, "%New", n, "%Plugin",
                            p.getName());
                }
                r.sendMes(cs, "pluginUpdatecheckallFinish", "%Amount", a);
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } //download
    else if (args[0].equalsIgnoreCase("download")) {
        if (!r.perm(cs, "uc.plugin.download", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDownload");
            cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core"
                    + r.negative + "/");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                String tag = args[1];
                r.sendMes(cs, "pluginDownloadGettingtag");
                String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss";
                String file;
                try {
                    final URL url = new URL(pluginUrlString);
                    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    final NodeList nodes = doc.getElementsByTagName("item");
                    final Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        final Element firstElement = (Element) firstNode;
                        final NodeList firstElementTagName = firstElement.getElementsByTagName("link");
                        final Element firstNameElement = (Element) firstElementTagName.item(0);
                        final NodeList firstNodes = firstNameElement.getChildNodes();
                        final String link = firstNodes.item(0).getNodeValue();
                        final URL dpage = new URL(link);
                        final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream()));
                        final StringBuilder content = new StringBuilder();
                        String inputLine;
                        while ((inputLine = br.readLine()) != null) {
                            content.append(inputLine);
                        }
                        br.close();
                        file = StringUtils.substringBetween(content.toString(),
                                "<li class=\"user-action user-action-download\"><span><a href=\"",
                                "\">Download</a></span></li>");
                    } else {
                        throw new Exception();
                    }
                } catch (Exception e) {
                    r.sendMes(cs, "pluginDownloadInvalidtag");
                    cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral
                            + "ultimate_core" + r.negative + "/");
                    return;
                }
                BufferedInputStream bis;
                final HttpURLConnection huc;
                try {
                    huc = (HttpURLConnection) new URL(file).openConnection();
                    huc.setInstanceFollowRedirects(true);
                    huc.connect();
                    bis = new BufferedInputStream(huc.getInputStream());
                } catch (MalformedURLException e) {
                    r.sendMes(cs, "pluginDownloadInvaliddownloadlink");
                    return;
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                String[] urlParts = huc.getURL().toString().split("(\\\\|/)");
                final String fileName = urlParts[urlParts.length - 1];
                r.sendMes(cs, "pluginDownloadCreatingTemp");
                File f = new File(System.getProperty("java.io.tmpdir") + File.separator
                        + UUID.randomUUID().toString() + File.separator + fileName);
                while (f.getParentFile().exists()) {
                    f = new File(System.getProperty("java.io.tmpdir") + File.separator
                            + UUID.randomUUID().toString() + File.separator + fileName);
                }
                if (!fileName.endsWith(".zip") && !fileName.endsWith(".jar")) {
                    r.sendMes(cs, "pluginDownloadNotJarOrZip", "%Filename", fileName);
                    return;
                }
                f.getParentFile().mkdirs();
                BufferedOutputStream bos;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(f));
                } catch (FileNotFoundException e) {
                    r.sendMes(cs, "pluginDownloadTempNotFound", "%Dir", System.getProperty("java.io.tmpdir"));
                    return;
                }
                int b;
                r.sendMes(cs, "pluginDownloadDownloading");
                try {
                    try {
                        while ((b = bis.read()) != -1) {
                            bos.write(b);
                        }
                    } finally {
                        bos.flush();
                        bos.close();
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                if (fileName.endsWith(".zip")) {
                    r.sendMes(cs, "pluginDownloadDecompressing");
                    PluginUtil.decompress(f.getAbsolutePath(), f.getParent());

                }
                String name = null;
                for (File fi : PluginUtil.listFiles(f.getParentFile())) {
                    if (!fi.getName().endsWith(".jar")) {
                        continue;
                    }
                    if (name == null) {
                        name = fi.getName();
                    }
                    r.sendMes(cs, "pluginDownloadMoving", "%File", fi.getName());
                    try {
                        Files.move(fi, new File(
                                r.getUC().getDataFolder().getParentFile() + File.separator + fi.getName()));
                    } catch (IOException e) {
                        r.sendMes(cs, "pluginDownloadCouldntMove", "%Message", e.getMessage());
                    }
                }
                PluginUtil.deleteDirectory(f.getParentFile());
                r.sendMes(cs, "pluginDownloadSucces", "%File", fileName);
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else if (args[0].equalsIgnoreCase("search")) {
        if (!r.perm(cs, "uc.plugin.search", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        int page = 1;
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpSearch");
            return;
        }
        Boolean b = false;
        if (r.checkArgs(args, 2)) {
            try {
                page = Integer.parseInt(args[args.length - 1]);
                b = true;
            } catch (NumberFormatException ignored) {
            }
        }
        String search = r.getFinalArg(args, 1);
        if (b) {
            search = new StringBuilder(new StringBuilder(search).reverse().toString()
                    .replaceFirst(new StringBuilder(" " + page).reverse().toString(), "")).reverse().toString();
        }
        try {
            search = URLEncoder.encode(search, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        final URL u;
        try {
            u = new URL("http://dev.bukkit.org/search/?scope=projects&search=" + search + "&page=" + page);
        } catch (MalformedURLException e) {
            r.sendMes(cs, "pluginSearchMalformedTerm");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                final BufferedReader br;
                try {
                    br = new BufferedReader(new InputStreamReader(u.openStream()));
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                String inputLine;
                StringBuilder content = new StringBuilder();
                try {
                    while ((inputLine = br.readLine()) != null) {
                        content.append(inputLine);
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                r.sendMes(cs, "pluginSearchHeader");
                for (int i = 0; i < 20; i++) {
                    final String project = StringUtils.substringBetween(content.toString(),
                            " row-joined-to-next\">", "</tr>");
                    final String base = StringUtils.substringBetween(project, "<td class=\"col-search-entry\">",
                            "</td>");
                    if (base == null) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final Pattern p = Pattern
                            .compile("<h2><a href=\"/bukkit-plugins/([\\W\\w]+)/\">([\\w\\W]+)</a></h2>");
                    final Matcher m = p.matcher(base);
                    if (!m.find()) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final String name = m.group(2).replaceAll("</?\\w+>", "");
                    final String tag = m.group(1);
                    final int beglen = StringUtils.substringBefore(content.toString(), base).length();
                    content = new StringBuilder(content.substring(beglen + project.length()));
                    r.sendMes(cs, "pluginSearchResult", "%Name", name, "%Tag", tag);
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else {
        cs.sendMessage(TextColors.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(TextColors.GOLD + "================================");
    }

}

From source file:bammerbom.ultimatecore.bukkit.commands.CmdPlugin.java

@Override
public void run(final CommandSender cs, String label, final String[] args) {
    //help/*from w w  w.  ja v  a 2 s. c o m*/
    if (!r.checkArgs(args, 0) || args[0].equalsIgnoreCase("help")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.help", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        cs.sendMessage(ChatColor.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(ChatColor.GOLD + "================================");
        return;
    } //load
    else if (args[0].equalsIgnoreCase("load")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.load", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpLoad");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile(),
                args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", args[1].endsWith(".jar") ? args[1] : args[1] + ".jar");
            return;
        }
        if (!f.canRead()) {
            r.sendMes(cs, "pluginFileNoReadAcces");
            return;
        }
        Plugin p;
        try {
            p = pm.loadPlugin(f);
            if (p == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependency", "%Message",
                    ex.getMessage() != null ? ex.getMessage() : "");
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginLoadSucces");
        } else {
            r.sendMes(cs, "pluginLoadFailed");
        }
        return;
    } //unload
    else if (args[0].equalsIgnoreCase("unload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.unload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUnload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(ChatColor.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependend", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        r.sendMes(cs, "pluginUnloadUnloading");
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        r.sendMes(cs, "pluginUnloadUnloaded");
        return;
    } //enable
    else if (args[0].equalsIgnoreCase("enable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.enable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpEnable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginAlreadyEnabled");
            return;
        }
        pm.enablePlugin(p);
        if (p.isEnabled()) {
            r.sendMes(cs, "pluginEnableSucces");
        } else {
            r.sendMes(cs, "pluginEnableFail");
        }
        return;
    } //disable
    else if (args[0].equalsIgnoreCase("disable")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.disable", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDisable");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        List<String> deps = PluginUtil.getDependedOnBy(p.getName());
        if (!deps.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String dep : deps) {
                sb.append(r.neutral);
                sb.append(dep);
                sb.append(ChatColor.RESET);
                sb.append(", ");
            }
            r.sendMes(cs, "pluginUnloadDependend", "%Plugins", sb.substring(0, sb.length() - 4));
            return;
        }
        pm.disablePlugin(p);
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginDisableSucces");
        } else {
            r.sendMes(cs, "pluginDisableFailed");
        }
        return;
    } //reload
    else if (args[0].equalsIgnoreCase("reload")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reload", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpReload");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        if (!p.isEnabled()) {
            r.sendMes(cs, "pluginNotEnabled");
            return;
        }
        pm.disablePlugin(p);
        pm.enablePlugin(p);
        r.sendMes(cs, "pluginReloadMessage");
        return;
    } //reloadall
    else if (args[0].equalsIgnoreCase("reloadall")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.reloadall", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        for (Plugin p : pm.getPlugins()) {
            pm.disablePlugin(p);
            pm.enablePlugin(p);
        }
        r.sendMes(cs, "pluginReloadallMessage");
        return;
    } //delete
    else if (args[0].equalsIgnoreCase("delete")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.delete", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDelete");
            return;
        }
        String del = args[1];
        if (!del.endsWith(".jar")) {
            del = del + ".jar";
        }
        if (del.contains(File.separator)) {
            r.sendMes(cs, "pluginDeleteDontLeavePluginFolder");
            return;
        }
        File f = new File(r.getUC().getDataFolder().getParentFile() + File.separator + del);
        if (!f.exists()) {
            r.sendMes(cs, "pluginFileNotFound", "%File", del);
            return;
        }
        if (f.delete()) {
            r.sendMes(cs, "pluginDeleteSucces");
        } else {
            r.sendMes(cs, "pluginDeleteFailed");
        }
        return;
    } //commands
    else if (args[0].equalsIgnoreCase("commands")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.commands", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpCommands");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        Map<String, Map<String, Object>> cmds = p.getDescription().getCommands();
        if (cmds == null) {
            r.sendMes(cs, "pluginCommandsNoneRegistered");
            return;
        }
        String command = "plugin " + p.getName();
        String pageStr = args.length > 2 ? args[2] : null;
        UText input = new TextInput(cs);
        UText output;
        if (input.getLines().isEmpty()) {
            if ((r.isInt(pageStr)) || (pageStr == null)) {
                output = new PluginCommandsInput(cs, args[1].toLowerCase());
            } else {
                r.sendMes(cs, "pluginCommandsPageNotNumber");
                return;
            }
        } else {
            output = input;
        }
        TextPager pager = new TextPager(output);
        pager.showPage(pageStr, null, command, cs);
        return;
    } //update
    else if (args[0].equalsIgnoreCase("update")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.update", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdate");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        URL u = Bukkit.getPluginManager().getPlugin("UltimateCore").getClass().getProtectionDomain()
                .getCodeSource().getLocation();
        File f;
        try {
            f = new File(u.toURI());
        } catch (URISyntaxException e) {
            f = new File(u.getPath());
        }
        PluginUtil.unregisterAllPluginCommands(p.getName());
        HandlerList.unregisterAll(p);
        Bukkit.getServicesManager().unregisterAll(p);
        Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(p);
        Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(p);
        Bukkit.getServer().getScheduler().cancelTasks(p);
        pm.disablePlugin(p);
        PluginUtil.removePluginFromList(p);
        try {
            Plugin p2 = pm.loadPlugin(f);
            if (p2 == null) {
                r.sendMes(cs, "pluginLoadFailed");
                return;
            }
            pm.enablePlugin(p2);
        } catch (UnknownDependencyException ex) {
            r.sendMes(cs, "pluginLoadMissingDependendy", "%Message", ex.getMessage());
            ex.printStackTrace();
            return;
        } catch (InvalidDescriptionException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        } catch (InvalidPluginException ex) {
            r.sendMes(cs, "pluginLoadFailed");
            ex.printStackTrace();
            return;
        }
        return;
    } //list
    else if (args[0].equalsIgnoreCase("list")) {
        if (!r.perm(cs, "uc.plugin", false, false) && !r.perm(cs, "uc.plugin.list", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        r.sendMes(cs, "pluginsList", "%Plugins", PluginUtil.getPluginList());
        return;
    } //info
    else if (args[0].equalsIgnoreCase("info")) {
        if (!r.perm(cs, "uc.plugin.info", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpInfo");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        PluginDescriptionFile pdf = p.getDescription();
        if (pdf == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        String version = pdf.getVersion();
        List<String> authors = pdf.getAuthors();
        String site = pdf.getWebsite();
        List<String> softDep = pdf.getSoftDepend();
        List<String> dep = pdf.getDepend();
        String name = pdf.getName();
        String desc = pdf.getDescription();
        if (name != null && !name.isEmpty()) {
            r.sendMes(cs, "pluginInfoName", "%Name", name);
        }
        if (version != null && !version.isEmpty()) {
            r.sendMes(cs, "pluginInfoVersion", "%Version", version);
        }
        if (site != null && !site.isEmpty()) {
            r.sendMes(cs, "pluginInfoWebsite", "%Website", site);
        }
        if (desc != null && !desc.isEmpty()) {
            r.sendMes(cs, "pluginInfoDescription", "%Description", desc.replaceAll("\r?\n", ""));
        }
        if (authors != null && !authors.isEmpty()) {
            r.sendMes(cs, "pluginInfoAuthor", "%S", ((authors.size() > 1) ? "s" : ""), "%Author",
                    StringUtil.join(ChatColor.RESET + ", " + r.neutral, authors));
        }
        if (softDep != null && !softDep.isEmpty()) {
            r.sendMes(cs, "pluginInfoSoftdeps", "%Softdeps",
                    StringUtil.join(ChatColor.RESET + ", " + r.neutral, softDep));
        }
        if (dep != null && !dep.isEmpty()) {
            r.sendMes(cs, "pluginInfoDeps", "%Deps", StringUtil.join(ChatColor.RESET + ", " + r.neutral, dep));
        }
        r.sendMes(cs, "pluginInfoEnabled", "%Enabled", ((p.isEnabled()) ? r.mes("yes") : r.mes("no")));
        return;
    } //updatecheck
    else if (args[0].equalsIgnoreCase("updatecheck")) {
        if (!r.perm(cs, "uc.plugin.updatecheck", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpUpdatecheck");
            return;
        }
        Plugin p = pm.getPlugin(args[1]);
        if (p == null) {
            r.sendMes(cs, "pluginNotFound", "%Plugin", args[1]);
            return;
        }
        final String tag;
        try {
            tag = URLEncoder.encode(r.checkArgs(args, 2) ? args[2] : p.getName(), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        if (p.getDescription() == null) {
            r.sendMes(cs, "pluginLoadInvalidDescription");
            return;
        }
        final String v = p.getDescription().getVersion() == null ? r.mes("pluginNotSet")
                : p.getDescription().getVersion();
        Runnable ru = new Runnable() {
            @Override
            public void run() {
                try {
                    String n = "";
                    String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/" + tag + "/files.rss";
                    URL url = new URL(pluginUrlString);
                    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    NodeList nodes = doc.getElementsByTagName("item");
                    Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        Element firstElement = (Element) firstNode;
                        NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                        Element firstNameElement = (Element) firstElementTagName.item(0);
                        NodeList firstNodes = firstNameElement.getChildNodes();
                        n = firstNodes.item(0).getNodeValue();
                    }

                    r.sendMes(cs, "pluginUpdatecheckCurrent", "%Current", v + "");
                    r.sendMes(cs, "pluginUpdatecheckNew", "%New", n + "");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    r.sendMes(cs, "pluginUpdatecheckFailed");
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
        return;
    } //updatecheckall
    else if (args[0].equalsIgnoreCase("updatecheckall")) {
        if (!r.perm(cs, "uc.plugin.updatecheckall", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (Plugin p : pm.getPlugins()) {
                    if (p.getDescription() == null) {
                        continue;
                    }
                    String version = p.getDescription().getVersion();
                    if (version == null) {
                        continue;
                    }
                    String n = "";
                    try {
                        String pluginUrlString = "http://dev.bukkit.org/bukkit-plugins/"
                                + p.getName().toLowerCase() + "/files.rss";
                        URL url = new URL(pluginUrlString);
                        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(url.openConnection().getInputStream());
                        doc.getDocumentElement().normalize();
                        NodeList nodes = doc.getElementsByTagName("item");
                        Node firstNode = nodes.item(0);
                        if (firstNode.getNodeType() == 1) {
                            Element firstElement = (Element) firstNode;
                            NodeList firstElementTagName = firstElement.getElementsByTagName("title");
                            Element firstNameElement = (Element) firstElementTagName.item(0);
                            NodeList firstNodes = firstNameElement.getChildNodes();
                            n = firstNodes.item(0).getNodeValue();
                            a++;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                    if (n.contains(version)) {
                        continue;
                    }
                    r.sendMes(cs, "pluginUpdatecheckallAvailable", "%Old", version, "%New", n, "%Plugin",
                            p.getName());
                }
                r.sendMes(cs, "pluginUpdatecheckallFinish", "%Amount", a);
                return;
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
        return;
    } //download
    else if (args[0].equalsIgnoreCase("download")) {
        if (!r.perm(cs, "uc.plugin.download", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpDownload");
            cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral + "ultimate_core"
                    + r.negative + "/");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                String tag = args[1];
                r.sendMes(cs, "pluginDownloadGettingtag");
                String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss";
                String file;
                try {
                    final URL url = new URL(pluginUrlString);
                    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(url.openConnection().getInputStream());
                    doc.getDocumentElement().normalize();
                    final NodeList nodes = doc.getElementsByTagName("item");
                    final Node firstNode = nodes.item(0);
                    if (firstNode.getNodeType() == 1) {
                        final Element firstElement = (Element) firstNode;
                        final NodeList firstElementTagName = firstElement.getElementsByTagName("link");
                        final Element firstNameElement = (Element) firstElementTagName.item(0);
                        final NodeList firstNodes = firstNameElement.getChildNodes();
                        final String link = firstNodes.item(0).getNodeValue();
                        final URL dpage = new URL(link);
                        final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream()));
                        final StringBuilder content = new StringBuilder();
                        String inputLine;
                        while ((inputLine = br.readLine()) != null) {
                            content.append(inputLine);
                        }
                        br.close();
                        file = StringUtils.substringBetween(content.toString(),
                                "<li class=\"user-action user-action-download\"><span><a href=\"",
                                "\">Download</a></span></li>");
                    } else {
                        throw new Exception();
                    }
                } catch (Exception e) {
                    r.sendMes(cs, "pluginDownloadInvalidtag");
                    cs.sendMessage(r.negative + "http://dev.bukkit.org/server-mods/" + r.neutral
                            + "ultimate_core" + r.negative + "/");
                    return;
                }
                BufferedInputStream bis;
                final HttpURLConnection huc;
                try {
                    huc = (HttpURLConnection) new URL(file).openConnection();
                    huc.setInstanceFollowRedirects(true);
                    huc.connect();
                    bis = new BufferedInputStream(huc.getInputStream());
                } catch (MalformedURLException e) {
                    r.sendMes(cs, "pluginDownloadInvaliddownloadlink");
                    return;
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                String[] urlParts = huc.getURL().toString().split("(\\\\|/)");
                final String fileName = urlParts[urlParts.length - 1];
                r.sendMes(cs, "pluginDownloadCreatingTemp");
                File f = new File(System.getProperty("java.io.tmpdir") + File.separator
                        + UUID.randomUUID().toString() + File.separator + fileName);
                while (f.getParentFile().exists()) {
                    f = new File(System.getProperty("java.io.tmpdir") + File.separator
                            + UUID.randomUUID().toString() + File.separator + fileName);
                }
                if (!fileName.endsWith(".zip") && !fileName.endsWith(".jar")) {
                    r.sendMes(cs, "pluginDownloadNotJarOrZip", "%Filename", fileName);
                    return;
                }
                f.getParentFile().mkdirs();
                BufferedOutputStream bos;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(f));
                } catch (FileNotFoundException e) {
                    r.sendMes(cs, "pluginDownloadTempNotFound", "%Dir", System.getProperty("java.io.tmpdir"));
                    return;
                }
                int b;
                r.sendMes(cs, "pluginDownloadDownloading");
                try {
                    try {
                        while ((b = bis.read()) != -1) {
                            bos.write(b);
                        }
                    } finally {
                        bos.flush();
                        bos.close();
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginDownloadFailed", "%Message", e.getMessage());
                    return;
                }
                if (fileName.endsWith(".zip")) {
                    r.sendMes(cs, "pluginDownloadDecompressing");
                    PluginUtil.decompress(f.getAbsolutePath(), f.getParent());

                }
                String name = null;
                for (File fi : PluginUtil.listFiles(f.getParentFile())) {
                    if (!fi.getName().endsWith(".jar")) {
                        continue;
                    }
                    if (name == null) {
                        name = fi.getName();
                    }
                    r.sendMes(cs, "pluginDownloadMoving", "%File", fi.getName());
                    try {
                        Files.move(fi, new File(
                                r.getUC().getDataFolder().getParentFile() + File.separator + fi.getName()));
                    } catch (IOException e) {
                        r.sendMes(cs, "pluginDownloadCouldntMove", "%Message", e.getMessage());
                    }
                }
                PluginUtil.deleteDirectory(f.getParentFile());
                r.sendMes(cs, "pluginDownloadSucces", "%File", fileName);
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else if (args[0].equalsIgnoreCase("search")) {
        if (!r.perm(cs, "uc.plugin.search", false, false) && !r.perm(cs, "uc.plugin", false, false)) {
            r.sendMes(cs, "noPermissions");
            return;
        }
        int page = 1;
        if (!r.checkArgs(args, 1)) {
            r.sendMes(cs, "pluginHelpSearch");
            return;
        }
        Boolean b = false;
        if (r.checkArgs(args, 2)) {
            try {
                page = Integer.parseInt(args[args.length - 1]);
                b = true;
            } catch (NumberFormatException ignored) {
            }
        }
        String search = r.getFinalArg(args, 1);
        if (b) {
            search = new StringBuilder(new StringBuilder(search).reverse().toString()
                    .replaceFirst(new StringBuilder(" " + page).reverse().toString(), "")).reverse().toString();
        }
        try {
            search = URLEncoder.encode(search, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            r.sendMes(cs, "pluginNoUTF8");
            return;
        }
        final URL u;
        try {
            u = new URL("http://dev.bukkit.org/search/?scope=projects&search=" + search + "&page=" + page);
        } catch (MalformedURLException e) {
            r.sendMes(cs, "pluginSearchMalformedTerm");
            return;
        }
        final Runnable ru = new Runnable() {
            @Override
            public void run() {
                final BufferedReader br;
                try {
                    br = new BufferedReader(new InputStreamReader(u.openStream()));
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                String inputLine;
                StringBuilder content = new StringBuilder();
                try {
                    while ((inputLine = br.readLine()) != null) {
                        content.append(inputLine);
                    }
                } catch (IOException e) {
                    r.sendMes(cs, "pluginSearchFailed", "%Message", e.getMessage());
                    return;
                }
                r.sendMes(cs, "pluginSearchHeader");
                for (int i = 0; i < 20; i++) {
                    final String project = StringUtils.substringBetween(content.toString(),
                            " row-joined-to-next\">", "</tr>");
                    final String base = StringUtils.substringBetween(project, "<td class=\"col-search-entry\">",
                            "</td>");
                    if (base == null) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final Pattern p = Pattern
                            .compile("<h2><a href=\"/bukkit-plugins/([\\W\\w]+)/\">([\\w\\W]+)</a></h2>");
                    final Matcher m = p.matcher(base);
                    if (!m.find()) {
                        if (i == 0) {
                            r.sendMes(cs, "pluginSearchNoResults");
                        }
                        return;
                    }
                    final String name = m.group(2).replaceAll("</?\\w+>", "");
                    final String tag = m.group(1);
                    final int beglen = StringUtils.substringBefore(content.toString(), base).length();
                    content = new StringBuilder(content.substring(beglen + project.length()));
                    r.sendMes(cs, "pluginSearchResult", "%Name", name, "%Tag", tag);
                }
            }
        };
        Bukkit.getServer().getScheduler().runTaskAsynchronously(r.getUC(), ru);
    } else {
        cs.sendMessage(ChatColor.GOLD + "================================");
        r.sendMes(cs, "pluginHelpLoad");
        r.sendMes(cs, "pluginHelpUnload");
        r.sendMes(cs, "pluginHelpEnable");
        r.sendMes(cs, "pluginHelpDisable");
        r.sendMes(cs, "pluginHelpReload");
        r.sendMes(cs, "pluginHelpReloadall");
        r.sendMes(cs, "pluginHelpDelete");
        r.sendMes(cs, "pluginHelpUpdate");
        r.sendMes(cs, "pluginHelpCommands");
        r.sendMes(cs, "pluginHelpList");
        r.sendMes(cs, "pluginHelpUpdatecheck");
        r.sendMes(cs, "pluginHelpUpdatecheckall");
        r.sendMes(cs, "pluginHelpDownload");
        r.sendMes(cs, "pluginHelpSearch");
        cs.sendMessage(ChatColor.GOLD + "================================");
        return;
    }

}