Example usage for java.lang NumberFormatException getLocalizedMessage

List of usage examples for java.lang NumberFormatException getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang NumberFormatException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:de.blinkt.openvpn.core.ConfigParser.java

@SuppressWarnings("ConstantConditions")
public VpnProfile convertProfile() throws ConfigParseError, IOException {
    boolean noauthtypeset = true;
    VpnProfile np = new VpnProfile(CONVERTED_PROFILE);
    // Pull, client, tls-client
    np.clearDefaults();//from ww  w  .j av a 2 s  .  co  m

    if (options.containsKey("client") || options.containsKey("pull")) {
        np.mUsePull = true;
        options.remove("pull");
        options.remove("client");
    }

    Vector<String> secret = getOption("secret", 1, 2);
    if (secret != null) {
        np.mAuthenticationType = VpnProfile.TYPE_STATICKEYS;
        noauthtypeset = false;
        np.mUseTLSAuth = true;
        np.mTLSAuthFilename = secret.get(1);
        if (secret.size() == 3)
            np.mTLSAuthDirection = secret.get(2);

    }

    Vector<Vector<String>> routes = getAllOption("route", 1, 4);
    if (routes != null) {
        String routeopt = "";
        String routeExcluded = "";
        for (Vector<String> route : routes) {
            String netmask = "255.255.255.255";
            String gateway = "vpn_gateway";

            if (route.size() >= 3)
                netmask = route.get(2);
            if (route.size() >= 4)
                gateway = route.get(3);

            String net = route.get(1);
            try {
                CIDRIP cidr = new CIDRIP(net, netmask);
                if (gateway.equals("net_gateway"))
                    routeExcluded += cidr.toString() + " ";
                else
                    routeopt += cidr.toString() + " ";
            } catch (ArrayIndexOutOfBoundsException aioob) {
                throw new ConfigParseError("Could not parse netmask of route " + netmask);
            } catch (NumberFormatException ne) {

                throw new ConfigParseError("Could not parse netmask of route " + netmask);
            }

        }
        np.mCustomRoutes = routeopt;
        np.mExcludedRoutes = routeExcluded;
    }

    Vector<Vector<String>> routesV6 = getAllOption("route-ipv6", 1, 4);
    if (routesV6 != null) {
        String customIPv6Routes = "";
        for (Vector<String> route : routesV6) {
            customIPv6Routes += route.get(1) + " ";
        }

        np.mCustomRoutesv6 = customIPv6Routes;
    }

    Vector<String> routeNoPull = getOption("route-nopull", 1, 1);
    if (routeNoPull != null)
        np.mRoutenopull = true;

    // Also recognize tls-auth [inline] direction ...
    Vector<Vector<String>> tlsauthoptions = getAllOption("tls-auth", 1, 2);
    if (tlsauthoptions != null) {
        for (Vector<String> tlsauth : tlsauthoptions) {
            if (tlsauth != null) {
                if (!tlsauth.get(1).equals("[inline]")) {
                    np.mTLSAuthFilename = tlsauth.get(1);
                    np.mUseTLSAuth = true;
                }
                if (tlsauth.size() == 3)
                    np.mTLSAuthDirection = tlsauth.get(2);
            }
        }
    }

    Vector<String> direction = getOption("key-direction", 1, 1);
    if (direction != null)
        np.mTLSAuthDirection = direction.get(1);

    Vector<Vector<String>> defgw = getAllOption("redirect-gateway", 0, 5);
    if (defgw != null) {
        np.mUseDefaultRoute = true;
        checkRedirectParameters(np, defgw);
    }

    Vector<Vector<String>> redirectPrivate = getAllOption("redirect-private", 0, 5);
    if (redirectPrivate != null) {
        checkRedirectParameters(np, redirectPrivate);
    }
    Vector<String> dev = getOption("dev", 1, 1);
    Vector<String> devtype = getOption("dev-type", 1, 1);

    if ((devtype != null && devtype.get(1).equals("tun")) || (dev != null && dev.get(1).startsWith("tun"))
            || (devtype == null && dev == null)) {
        //everything okay
    } else {
        throw new ConfigParseError("Sorry. Only tun mode is supported. See the FAQ for more detail");
    }

    Vector<String> mssfix = getOption("mssfix", 0, 1);

    if (mssfix != null) {
        if (mssfix.size() >= 2) {
            try {
                np.mMssFix = Integer.parseInt(mssfix.get(1));
            } catch (NumberFormatException e) {
                throw new ConfigParseError("Argument to --mssfix has to be an integer");
            }
        } else {
            np.mMssFix = 1450; // OpenVPN default size
        }
    }

    Vector<String> mode = getOption("mode", 1, 1);
    if (mode != null) {
        if (!mode.get(1).equals("p2p"))
            throw new ConfigParseError("Invalid mode for --mode specified, need p2p");
    }

    Vector<Vector<String>> dhcpoptions = getAllOption("dhcp-option", 2, 2);
    if (dhcpoptions != null) {
        for (Vector<String> dhcpoption : dhcpoptions) {
            String type = dhcpoption.get(1);
            String arg = dhcpoption.get(2);
            if (type.equals("DOMAIN")) {
                np.mSearchDomain = dhcpoption.get(2);
            } else if (type.equals("DNS")) {
                np.mOverrideDNS = true;
                if (np.mDNS1.equals(VpnProfile.DEFAULT_DNS1))
                    np.mDNS1 = arg;
                else
                    np.mDNS2 = arg;
            }
        }
    }

    Vector<String> ifconfig = getOption("ifconfig", 2, 2);
    if (ifconfig != null) {
        try {
            CIDRIP cidr = new CIDRIP(ifconfig.get(1), ifconfig.get(2));
            np.mIPv4Address = cidr.toString();
        } catch (NumberFormatException nfe) {
            throw new ConfigParseError("Could not pase ifconfig IP address: " + nfe.getLocalizedMessage());
        }

    }

    if (getOption("remote-random-hostname", 0, 0) != null)
        np.mUseRandomHostname = true;

    if (getOption("float", 0, 0) != null)
        np.mUseFloat = true;

    if (getOption("comp-lzo", 0, 1) != null)
        np.mUseLzo = true;

    Vector<String> cipher = getOption("cipher", 1, 1);
    if (cipher != null)
        np.mCipher = cipher.get(1);

    Vector<String> auth = getOption("auth", 1, 1);
    if (auth != null)
        np.mAuth = auth.get(1);

    Vector<String> ca = getOption("ca", 1, 1);
    if (ca != null) {
        np.mCaFilename = ca.get(1);
    }

    Vector<String> cert = getOption("cert", 1, 1);
    if (cert != null) {
        np.mClientCertFilename = cert.get(1);
        np.mAuthenticationType = VpnProfile.TYPE_CERTIFICATES;
        noauthtypeset = false;
    }
    Vector<String> key = getOption("key", 1, 1);
    if (key != null)
        np.mClientKeyFilename = key.get(1);

    Vector<String> pkcs12 = getOption("pkcs12", 1, 1);
    if (pkcs12 != null) {
        np.mPKCS12Filename = pkcs12.get(1);
        np.mAuthenticationType = VpnProfile.TYPE_KEYSTORE;
        noauthtypeset = false;
    }

    Vector<String> cryptoapicert = getOption("cryptoapicert", 1, 1);
    if (cryptoapicert != null) {
        np.mAuthenticationType = VpnProfile.TYPE_KEYSTORE;
        noauthtypeset = false;
    }

    Vector<String> compatnames = getOption("compat-names", 1, 2);
    Vector<String> nonameremapping = getOption("no-name-remapping", 1, 1);
    Vector<String> tlsremote = getOption("tls-remote", 1, 1);
    if (tlsremote != null) {
        np.mRemoteCN = tlsremote.get(1);
        np.mCheckRemoteCN = true;
        np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE;

        if ((compatnames != null && compatnames.size() > 2) || (nonameremapping != null))
            np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING;
    }

    Vector<String> verifyx509name = getOption("verify-x509-name", 1, 2);
    if (verifyx509name != null) {
        np.mRemoteCN = verifyx509name.get(1);
        np.mCheckRemoteCN = true;
        if (verifyx509name.size() > 2) {
            if (verifyx509name.get(2).equals("name"))
                np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_RDN;
            else if (verifyx509name.get(2).equals("subject"))
                np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_DN;
            else if (verifyx509name.get(2).equals("name-prefix"))
                np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX;
            else
                throw new ConfigParseError("Unknown parameter to verify-x509-name: " + verifyx509name.get(2));
        } else {
            np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_DN;
        }

    }

    Vector<String> x509usernamefield = getOption("x509-username-field", 1, 1);
    if (x509usernamefield != null) {
        np.mx509UsernameField = x509usernamefield.get(1);
    }

    Vector<String> verb = getOption("verb", 1, 1);
    if (verb != null) {
        np.mVerb = verb.get(1);
    }

    if (getOption("nobind", 0, 0) != null)
        np.mNobind = true;

    if (getOption("persist-tun", 0, 0) != null)
        np.mPersistTun = true;

    if (getOption("push-peer-info", 0, 0) != null)
        np.mPushPeerInfo = true;

    Vector<String> connectretry = getOption("connect-retry", 1, 2);
    if (connectretry != null) {
        np.mConnectRetry = connectretry.get(1);
        if (connectretry.size() > 2)
            np.mConnectRetryMaxTime = connectretry.get(2);
    }

    Vector<String> connectretrymax = getOption("connect-retry-max", 1, 1);
    if (connectretrymax != null)
        np.mConnectRetryMax = connectretrymax.get(1);

    Vector<Vector<String>> remotetls = getAllOption("remote-cert-tls", 1, 1);
    if (remotetls != null)
        if (remotetls.get(0).get(1).equals("server"))
            np.mExpectTLSCert = true;
        else
            options.put("remotetls", remotetls);

    Vector<String> authuser = getOption("auth-user-pass", 0, 1);

    if (authuser != null) {
        if (noauthtypeset) {
            np.mAuthenticationType = VpnProfile.TYPE_USERPASS;
        } else if (np.mAuthenticationType == VpnProfile.TYPE_CERTIFICATES) {
            np.mAuthenticationType = VpnProfile.TYPE_USERPASS_CERTIFICATES;
        } else if (np.mAuthenticationType == VpnProfile.TYPE_KEYSTORE) {
            np.mAuthenticationType = VpnProfile.TYPE_USERPASS_KEYSTORE;
        }
        if (authuser.size() > 1) {
            if (!authuser.get(1).startsWith(VpnProfile.INLINE_TAG))
                auth_user_pass_file = authuser.get(1);
            np.mUsername = null;
            useEmbbedUserAuth(np, authuser.get(1));
        }
    }

    Vector<String> crlfile = getOption("crl-verify", 1, 2);
    if (crlfile != null) {
        // If the 'dir' parameter is present just add it as custom option ..
        if (crlfile.size() == 3 && crlfile.get(2).equals("dir"))
            np.mCustomConfigOptions += TextUtils.join(" ", crlfile) + "\n";
        else
            // Save the filename for the config converter to add later
            np.mCrlFilename = crlfile.get(1);

    }

    Pair<Connection, Connection[]> conns = parseConnectionOptions(null);
    np.mConnections = conns.second;

    Vector<Vector<String>> connectionBlocks = getAllOption("connection", 1, 1);

    if (np.mConnections.length > 0 && connectionBlocks != null) {
        throw new ConfigParseError("Using a <connection> block and --remote is not allowed.");
    }

    if (connectionBlocks != null) {
        np.mConnections = new Connection[connectionBlocks.size()];

        int connIndex = 0;
        for (Vector<String> conn : connectionBlocks) {
            Pair<Connection, Connection[]> connectionBlockConnection = parseConnection(conn.get(1),
                    conns.first);

            if (connectionBlockConnection.second.length != 1)
                throw new ConfigParseError("A <connection> block must have exactly one remote");
            np.mConnections[connIndex] = connectionBlockConnection.second[0];
            connIndex++;
        }
    }
    if (getOption("remote-random", 0, 0) != null)
        np.mRemoteRandom = true;

    Vector<String> protoforce = getOption("proto-force", 1, 1);
    if (protoforce != null) {
        boolean disableUDP;
        String protoToDisable = protoforce.get(1);
        if (protoToDisable.equals("udp"))
            disableUDP = true;
        else if (protoToDisable.equals("tcp"))
            disableUDP = false;
        else
            throw new ConfigParseError(String.format("Unknown protocol %s in proto-force", protoToDisable));

        for (Connection conn : np.mConnections)
            if (conn.mUseUdp == disableUDP)
                conn.mEnabled = false;
    }

    // Parse OpenVPN Access Server extra
    Vector<String> friendlyname = meta.get("FRIENDLY_NAME");
    if (friendlyname != null && friendlyname.size() > 1)
        np.mName = friendlyname.get(1);

    Vector<String> ocusername = meta.get("USERNAME");
    if (ocusername != null && ocusername.size() > 1)
        np.mUsername = ocusername.get(1);

    checkIgnoreAndInvalidOptions(np);
    fixup(np);

    return np;
}

From source file:op.care.nursingprocess.PnlSchedule.java

private void btnSaveActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    try {//from w  w  w  .ja  v  a 2s  .c  om
        save();
        actionBlock.execute(is);
    } catch (NumberFormatException nfe) {
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                SYSTools.xx(internalClassID + ".parseerror") + nfe.getLocalizedMessage(), 2));
    }
}

From source file:de.dmarcini.submatix.pclogger.gui.spx42LogGraphPanel.java

/**
 * Anhand des Alias des Gertes die Tauchgangsliste fllen Project: SubmatixBTForPC Package: de.dmarcini.submatix.pclogger.gui
 * //from   w ww.jav a  2s .  c om
 * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 02.07.2012
 * @param deviceAlias
 */
@SuppressWarnings("unchecked")
private void fillDiveComboBox(String cDevice) {
    String device;
    DateTime dateTime;
    long javaTime;
    //
    device = cDevice;
    if (device != null) {
        lg.debug("search dive list for device <" + device + ">...");
        releaseGraph();
        // Eine Liste der Dives lesen
        lg.debug("read dive list for device from DB...");
        Vector<String[]> entrys = databaseUtil.getDiveListForDeviceLog(device);
        if (entrys.size() < 1) {
            lg.info("no dives for device <" + cDevice + "/" + databaseUtil.getAliasForNameConn(device)
                    + "> found in DB.");
            clearDiveComboBox();
            return;
        }
        //
        // Objekt fr das Modell erstellen
        Vector<String[]> diveEntrys = new Vector<String[]>();
        // die erfragten details zurechtrcken
        // Felder sind:
        // H_DIVEID,
        // H_H_DIVENUMBERONSPX
        // H_STARTTIME,
        for (Enumeration<String[]> enu = entrys.elements(); enu.hasMoreElements();) {
            String[] origSet = enu.nextElement();
            // zusammenbauen fuer Anzeige
            String[] elem = new String[3];
            // SPX-DiveNumber etwas einrcken, fr vierstellige Anzeige
            elem[0] = origSet[0];
            elem[1] = String.format("%4s", origSet[1]);
            // Die UTC-Zeit als ASCII/UNIX wieder zu der originalen Zeit fr Java zusammenbauen
            try {
                javaTime = Long.parseLong(origSet[2]) * 1000;
                dateTime = new DateTime(javaTime);
                elem[2] = dateTime.toString(LangStrings.getString("MainCommGUI.timeFormatterString"));
            } catch (NumberFormatException ex) {
                lg.error("Number format exception (value=<" + origSet[1] + ">: <" + ex.getLocalizedMessage()
                        + ">");
                elem[1] = "error";
            }
            diveEntrys.add(elem);
        }
        // aufrumen
        entrys.clear();
        entrys = null;
        // die box initialisieren
        LogListComboBoxModel listBoxModel = new LogListComboBoxModel(diveEntrys);
        diveSelectComboBox.setModel(listBoxModel);
        if (diveEntrys.size() > 0) {
            diveSelectComboBox.setSelectedIndex(0);
        }
    } else {
        lg.debug("no device found....");
    }
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Regenerate descriptors for the experiments contained in the given file tree.
 * @return List of descriptor paths/*from   www  .  ja va  2s  . c  o  m*/
 * @throws Exception 
 * @throws IOException 
 */
public List<String> regeneratePublishedDescriptors() throws Exception {
    String descriptorPath = null;
    int depth = 0;
    List<String> descriptorsPath = experimentListXml.getExperimentList();
    List<ExperimentFolder> experiments = experimentListXml.readExperiments(this.outputToConsole);
    for (ExperimentFolder experiment : experiments) {
        try {
            //load parsing configuration previously used
            String parsingRuleSetFilePath = null;
            String softwareContext = null;
            Properties parsingConfig = loadParsingConfigFile(experiment.getFileDirectory().getAbsolutePath()
                    + PATH_FOLDER_SEPARATOR + IBIOMES_PARSE_CONFIG_FILE_NAME);
            if (parsingConfig != null) {
                parsingRuleSetFilePath = parsingConfig.getProperty(PARSER_CONFIG_PROPERTY_RULE_SET_FILE);
                softwareContext = parsingConfig.getProperty(PARSER_CONFIG_PROPERTY_SOFTWARE_CONTEXT);
                try {
                    depth = Integer
                            .parseInt(parsingConfig.getProperty(PARSER_CONFIG_PROPERTY_SOFTWARE_CONTEXT));
                } catch (NumberFormatException e) {
                    //TODO
                }
            }
            //parse
            descriptorPath = experiment.getFileDirectory().getAbsolutePath() + PATH_FOLDER_SEPARATOR
                    + IBIOMES_DESC_FILE_TREE_FILE_NAME;
            this.parse(experiment.getFileDirectory().getAbsolutePath(), softwareContext, parsingRuleSetFilePath,
                    depth);
            experiment.getFileDirectory().storeToXML(descriptorPath);
        } catch (Exception e) {
            //logger
            System.err
                    .println("[ERROR] Error when updating '" + descriptorPath + "':" + e.getLocalizedMessage());
        }
    }
    return descriptorsPath;
}

From source file:nf.frex.android.FrexActivity.java

private void preparePropertiesDialog(final Dialog dialog) {

    final Registry<Fractal> fractals = Registries.fractals;
    int fractalTypeIndex = fractals.getIndex(view.getFractalId());

    final Spinner fractalTypeSpinner = (Spinner) dialog.findViewById(R.id.fractal_type_spinner);
    final SeekBar iterationsSeekBar = (SeekBar) dialog.findViewById(R.id.num_iterations_seek_bar);
    final EditText iterationsEditText = (EditText) dialog.findViewById(R.id.num_iterations_edit_text);
    final CheckBox juliaModeCheckBox = (CheckBox) dialog.findViewById(R.id.julia_mode_fractal_check_box);
    final CheckBox decoratedFractal = (CheckBox) dialog.findViewById(R.id.decorated_fractal_check_box);
    final Button okButton = (Button) dialog.findViewById(R.id.ok_button);
    final Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);

    juliaModeCheckBox.setEnabled(true);//from  w w w . j a  va  2  s . co m

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            fractals.getIds());
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    fractalTypeSpinner.setAdapter(arrayAdapter);
    fractalTypeSpinner.setSelection(fractalTypeIndex, true);
    fractalTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View spinnerView, int position, long id) {
            Fractal fractal = fractals.getValue(position);
            iterationsEditText.setText(fractal.getDefaultIterMax() + "");
            boolean sameFractal = view.getFractalId().equals(fractals.getId(position));
            if (!sameFractal) {
                juliaModeCheckBox.setChecked(false);
            }
            juliaModeCheckBox.setEnabled(sameFractal);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    iterationsEditText.setText(view.getIterMax() + "", TextView.BufferType.NORMAL);

    final double iterationsMin = 1;
    final double iterationsMax = 3;
    final SeekBarConfigurer iterationsSeekBarConfigurer = SeekBarConfigurer.create(iterationsSeekBar,
            iterationsMin, iterationsMax, true, view.getIterMax());
    iterationsSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                int iterMax = iterationsSeekBarConfigurer.getValueInt();
                iterationsEditText.setText(iterMax + "", TextView.BufferType.NORMAL);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    iterationsEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            try {
                int iterMax = Integer.parseInt(v.getText().toString());
                iterationsSeekBarConfigurer.setValue(iterMax);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    });

    decoratedFractal.setChecked(view.isDecoratedFractal());

    juliaModeCheckBox.setChecked(view.isJuliaModeFractal());

    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int iterMax;
            try {
                iterMax = Integer.parseInt(iterationsEditText.getText().toString());
            } catch (NumberFormatException e) {
                Toast.makeText(FrexActivity.this, getString(R.string.error_msg, e.getLocalizedMessage()),
                        Toast.LENGTH_SHORT).show();
                return;
            }
            dialog.dismiss();
            String oldConfigName = view.getConfigName();
            String newFractalId = fractals.getId(fractalTypeSpinner.getSelectedItemPosition());
            Fractal fractal = fractals.getValue(fractalTypeSpinner.getSelectedItemPosition());
            String oldFractalId = view.getFractalId();
            boolean newJuliaModeFractal = juliaModeCheckBox.isChecked();
            boolean oldJuliaModeFractal = view.isJuliaModeFractal();
            view.setFractalId(newFractalId);
            view.setIterMax(iterMax);
            view.setDecoratedFractal(decoratedFractal.isChecked());
            view.setJuliaModeFractal(newJuliaModeFractal);
            boolean fractalTypeChanged = !oldFractalId.equals(newFractalId);
            if (fractalTypeChanged) {
                if (oldConfigName.contains(oldFractalId.toLowerCase())) {
                    view.setConfigName(newFractalId.toLowerCase());
                }
                view.setRegion(fractal.getDefaultRegion());
                view.setBailOut(fractal.getDefaultBailOut());
            }
            boolean juliaModeChanged = oldJuliaModeFractal != newJuliaModeFractal;
            if (fractalTypeChanged || juliaModeChanged) {
                view.getRegionHistory().clear();
                view.getRegionHistory().add(fractal.getDefaultRegion().clone());
            }
            view.recomputeAll();
        }
    });
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SelectCMFListener.java

public boolean checkFormat(File file) {
    boolean isSubjectIdSet = false;
    try {/* www .  j a va  2 s .co  m*/
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = br.readLine();
        while ((line = br.readLine()) != null) {
            if (line.compareTo("") != 0) {
                String[] fields = line.split("\t", -1);
                //check columns number
                if (fields.length != 6) {
                    this.selectCMFUI.displayMessage("Error:\nLines have not the right number of columns");
                    br.close();
                    return false;
                }
                //check raw file names
                if (!((ClinicalData) this.dataType).getRawFilesNames().contains(fields[0])) {
                    this.selectCMFUI.displayMessage("Error:\nData file '" + fields[0] + "' does not exist");
                    br.close();
                    return false;
                }
                //check that subject identifier is set
                if (fields[3].compareTo("SUBJ_ID") == 0) {
                    isSubjectIdSet = true;
                }
                //check that column number is set and is a number
                if (fields[2].compareTo("") == 0) {
                    this.selectCMFUI.displayMessage("Error:\nColumns numbers have to be set");
                    br.close();
                    return false;
                }
                try {
                    Integer.parseInt(fields[2]);
                } catch (NumberFormatException e) {
                    this.selectCMFUI.displayMessage("Error:\nColumns numbers have to be numbers");
                    br.close();
                    return false;
                }
                //check that datalabel is set
                if (fields[3].compareTo("") == 0) {
                    this.selectCMFUI.displayMessage("Error:\nData labels have to be set");
                    br.close();
                    return false;
                }
                //check that category code is set, except for reserved words
                if (!(fields[3].compareTo("SUBJ_ID") == 0 || fields[3].compareTo("OMIT") == 0
                        || fields[3].compareTo("SITE_ID") == 0 || fields[3].compareTo("VISIT_NAME") == 0)
                        && fields[1].compareTo("") == 0) {
                    this.selectCMFUI.displayMessage("Error:\nCategory codes have to be set");
                    br.close();
                    return false;
                }
                //check that data label source is set if the data label is '\'
                if (fields[3].compareTo("\\") == 0 && fields[4].compareTo("") == 0) {
                    this.selectCMFUI.displayMessage("Error:\nData label sources have to be set");
                    br.close();
                    return false;
                }
            }
        }
        br.close();
    } catch (Exception e) {
        this.selectCMFUI.displayMessage("File error: " + e.getLocalizedMessage());
        e.printStackTrace();
        return false;
    }
    if (!isSubjectIdSet) {
        this.selectCMFUI.displayMessage("Error:\nSubject identifiers have to be set");
        return false;
    }
    return true;
}

From source file:org.apache.axis2.transport.rabbitmq.RabbitMQSender.java

private void processResponse(RabbitMQConnectionFactory factory, MessageContext msgContext, String correlationID,
        String replyTo, Hashtable<String, String> eprProperties) throws IOException {

    Connection connection = factory.createConnection();

    if (!RabbitMQUtils.isQueueAvailable(connection, replyTo)) {
        log.info("Reply-to queue : " + replyTo + " not available, hence creating a new one");
        RabbitMQUtils.declareQueue(connection, replyTo, eprProperties);
    }/*  ww w.j a v a 2s.c  om*/

    Channel channel = connection.createChannel();
    QueueingConsumer consumer = new QueueingConsumer(channel);
    QueueingConsumer.Delivery delivery = null;
    RabbitMQMessage message = new RabbitMQMessage();
    boolean responseFound = false;

    int timeout = RabbitMQConstants.DEFAULT_REPLY_TO_TIMEOUT;
    String timeoutStr = eprProperties.get(RabbitMQConstants.REPLY_TO_TIMEOUT);
    if (!StringUtils.isEmpty(timeoutStr)) {
        try {
            timeout = Integer.parseInt(timeoutStr);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading replyto timeout value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    //start consuming without acknowledging
    String consumerTag = channel.basicConsume(replyTo, false, consumer);

    try {
        while (!responseFound) {
            log.debug("Waiting for next delivery from reply to queue " + replyTo);
            delivery = consumer.nextDelivery(timeout);
            if (delivery != null) {
                if (delivery.getProperties().getCorrelationId().equals(correlationID)) {
                    responseFound = true;
                    log.debug(
                            "Found matching response with correlation ID : " + correlationID + ". Sending ack");
                    //acknowledge correct message
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } else {
                    //not acknowledge wrong messages and re-queue
                    log.debug("Found messages with wrong correlation ID. Re-queueing and sending nack");
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
                }
            }
        }
    } catch (ShutdownSignalException e) {
        log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage());
    } catch (InterruptedException e) {
        log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage());
    } catch (ConsumerCancelledException e) {
        log.error("Error receiving message from RabbitMQ broker" + e.getLocalizedMessage());
    } finally {
        if (channel != null || channel.isOpen()) {
            //stop consuming
            channel.basicCancel(consumerTag);
        }
    }

    if (delivery != null) {
        log.debug("Processing response from reply-to queue");
        AMQP.BasicProperties properties = delivery.getProperties();
        Map<String, Object> headers = properties.getHeaders();
        message.setBody(delivery.getBody());
        message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag());
        message.setReplyTo(properties.getReplyTo());
        message.setMessageId(properties.getMessageId());

        //get content type from message
        String contentType = properties.getContentType();
        if (contentType == null) {
            //if not get content type from transport parameter
            contentType = eprProperties.get(RabbitMQConstants.REPLY_TO_CONTENT_TYPE);
            if (contentType == null) {
                //if none is given, set to default content type
                log.warn("Setting default content type " + RabbitMQConstants.DEFAULT_CONTENT_TYPE);
                contentType = RabbitMQConstants.DEFAULT_CONTENT_TYPE;
            }
        }
        message.setContentType(contentType);
        message.setContentEncoding(properties.getContentEncoding());
        message.setCorrelationId(properties.getCorrelationId());

        if (headers != null) {
            message.setHeaders(headers);
            if (headers.get(RabbitMQConstants.SOAP_ACTION) != null) {
                message.setSoapAction(headers.get(RabbitMQConstants.SOAP_ACTION).toString());
            }
        }

        MessageContext responseMsgCtx = createResponseMessageContext(msgContext);
        RabbitMQUtils.setSOAPEnvelope(message, responseMsgCtx, contentType);
        handleIncomingMessage(responseMsgCtx, RabbitMQUtils.getTransportHeaders(message),
                message.getSoapAction(), message.getContentType());
    }
}

From source file:org.apache.axis2.transport.rabbitmq.rpc.RabbitMQRPCMessageSender.java

private RabbitMQMessage processResponse(String correlationID) throws IOException {

    QueueingConsumer consumer = dualChannel.getConsumer();
    QueueingConsumer.Delivery delivery = null;
    RabbitMQMessage message = new RabbitMQMessage();
    String replyToQueue = dualChannel.getReplyToQueue();

    String queueAutoDeclareStr = epProperties.get(RabbitMQConstants.QUEUE_AUTODECLARE);
    boolean queueAutoDeclare = true;

    if (!StringUtils.isEmpty(queueAutoDeclareStr)) {
        queueAutoDeclare = Boolean.parseBoolean(queueAutoDeclareStr);
    }//w  w w . j  a  v a 2  s  .  c  o m

    if (queueAutoDeclare && !RabbitMQUtils.isQueueAvailable(dualChannel.getChannel(), replyToQueue)) {
        log.info("Reply-to queue : " + replyToQueue + " not available, hence creating a new one");
        RabbitMQUtils.declareQueue(dualChannel, replyToQueue, epProperties);
    }

    int timeout = RabbitMQConstants.DEFAULT_REPLY_TO_TIMEOUT;
    String timeoutStr = epProperties.get(RabbitMQConstants.REPLY_TO_TIMEOUT);
    if (!StringUtils.isEmpty(timeoutStr)) {
        try {
            timeout = Integer.parseInt(timeoutStr);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading replyto timeout value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    try {
        if (log.isDebugEnabled()) {
            log.debug(
                    "Waiting for delivery from reply to queue " + replyToQueue + " corr id : " + correlationID);
        }
        delivery = consumer.nextDelivery(timeout);
        if (delivery != null) {
            if (!StringUtils.isEmpty(delivery.getProperties().getCorrelationId())) {
                if (delivery.getProperties().getCorrelationId().equals(correlationID)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Found matching response with correlation ID : " + correlationID + ".");
                    }
                } else {
                    log.error("Response not queued in " + replyToQueue + " for correlation ID : "
                            + correlationID);
                    return null;
                }
            }
        } else {
            log.error("Response not queued in " + replyToQueue);
        }
    } catch (ShutdownSignalException e) {
        log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage());
    } catch (InterruptedException e) {
        log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage());
    } catch (ConsumerCancelledException e) {
        log.error("Error receiving message from RabbitMQ broker" + e.getLocalizedMessage());
    }

    if (delivery != null) {
        log.debug("Processing response from reply-to queue");
        AMQP.BasicProperties properties = delivery.getProperties();
        Map<String, Object> headers = properties.getHeaders();
        message.setBody(delivery.getBody());
        message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag());
        message.setReplyTo(properties.getReplyTo());
        message.setMessageId(properties.getMessageId());

        //get content type from message
        String contentType = properties.getContentType();
        if (contentType == null) {
            //if not get content type from transport parameter
            contentType = epProperties.get(RabbitMQConstants.REPLY_TO_CONTENT_TYPE);
            if (contentType == null) {
                //if none is given, set to default content type
                log.warn("Setting default content type " + RabbitMQConstants.DEFAULT_CONTENT_TYPE);
                contentType = RabbitMQConstants.DEFAULT_CONTENT_TYPE;
            }
        }
        message.setContentType(contentType);
        message.setContentEncoding(properties.getContentEncoding());
        message.setCorrelationId(properties.getCorrelationId());

        if (headers != null) {
            message.setHeaders(headers);
            if (headers.get(RabbitMQConstants.SOAP_ACTION) != null) {
                message.setSoapAction(headers.get(RabbitMQConstants.SOAP_ACTION).toString());
            }
        }
    }
    return message;
}

From source file:org.opencms.workplace.CmsWorkplaceManager.java

/**
 * Sets the value (in kb) for the maximum file upload size.<p>
 * /*w  ww .  j  a  va 2s.  c  o m*/
 * @param value the value (in kb) for the maximum file upload size
 */
public void setFileMaxUploadSize(String value) {

    try {
        m_fileMaxUploadSize = Integer.valueOf(value).intValue();
    } catch (NumberFormatException e) {
        // can usually be ignored
        if (LOG.isInfoEnabled()) {
            LOG.info(e.getLocalizedMessage());
        }
        m_fileMaxUploadSize = -1;
    }
    if (CmsLog.INIT.isInfoEnabled()) {
        if (m_fileMaxUploadSize > 0) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_MAX_FILE_UPLOAD_SIZE_1,
                    new Integer(m_fileMaxUploadSize)));
        } else {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_MAX_FILE_UPLOAD_SIZE_UNLIMITED_0));
        }

    }
}

From source file:org.eclipse.jubula.rc.common.commands.CapTestCommand.java

/**
 * Gets the implementation class. /*from  w w  w  . j  a  v a  2 s .  c om*/
 * @param response The response message.
 * @return the implementation class or null if an error occurs.
 */
protected Object getImplClass(CAPTestResponseMessage response) {
    Object implClass = null;
    final MessageCap messageCap = m_capTestMessage.getMessageCap();
    IComponentIdentifier ci = messageCap.getCi();
    if (LOG.isInfoEnabled()) {
        LOG.info("component class name: " //$NON-NLS-1$
                + (ci == null ? "(none)" : ci.getComponentClassName())); //$NON-NLS-1$
    }
    try {
        if (!messageCap.hasDefaultMapping()) {
            Validate.notNull(ci);
        }
        // FIXME : Extra handling for waitForComponent and verifyExists
        int timeout = TimingConstantsServer.DEFAULT_FIND_COMPONENT_TIMEOUT;
        boolean isWaitForComponent = WidgetTester.RC_METHOD_NAME_WAIT_FOR_COMPONENT
                .equals(messageCap.getMethod());
        if (isWaitForComponent) {
            MessageParam timeoutParam = messageCap.getMessageParams().get(0);
            try {
                timeout = Integer.parseInt(timeoutParam.getValue());
            } catch (NumberFormatException e) {
                LOG.warn("Error while parsing timeout parameter. " //$NON-NLS-1$
                        + "Using default value.", e); //$NON-NLS-1$
            }
        }
        final AUTServerConfiguration rcConfig = AUTServerConfiguration.getInstance();
        if (!messageCap.hasDefaultMapping()) {
            Object component = AUTServer.getInstance().findComponent(ci, timeout);
            implClass = rcConfig.prepareImplementationClass(component, component.getClass());
        } else {
            implClass = rcConfig.getImplementationClass(ci.getComponentClassName());
        }
        if (isWaitForComponent) {
            MessageParam delayParam = messageCap.getMessageParams().get(1);
            try {
                int delay = Integer.parseInt(delayParam.getValue());
                TimeUtil.delay(delay);
            } catch (IllegalArgumentException iae) {
                handleInvalidInput("Invalid input: " //$NON-NLS-1$
                        + CompSystemI18n.getString("CompSystem.DelayAfterVisibility") //$NON-NLS-1$
                        + " must be a non-negative integer."); //$NON-NLS-1$
            }
        }
    } catch (IllegalArgumentException e) {
        handleComponentNotFound(response, e);
    } catch (ComponentNotFoundException e) {
        if (WidgetTester.RC_METHOD_NAME_CHECK_EXISTENCE.equals(messageCap.getMethod())) {
            MessageParam isVisibleParam = messageCap.getMessageParams().get(0);
            handleComponentDoesNotExist(response, Boolean.valueOf(isVisibleParam.getValue()).booleanValue());
        } else {
            handleComponentNotFound(response, e);
        }
    } catch (UnsupportedComponentException buce) {
        LOG.error(buce.getLocalizedMessage(), buce);
        response.setTestErrorEvent(EventFactory.createConfigErrorEvent());
    } catch (Throwable e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        response.setTestErrorEvent(EventFactory.createImplClassErrorEvent());
    }
    return implClass;
}