Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.alfresco.filesys.auth.PassthruServerFactory.java

public void afterPropertiesSet() throws InvalidConfigurationException {
    // Check if the offline check interval has been specified
    if (this.offlineCheckInterval != null) {
        // Range check the value

        if (this.offlineCheckInterval < MinCheckInterval || this.offlineCheckInterval > MaxCheckInterval)
            throw new InvalidConfigurationException("Invalid offline check interval, valid range is "
                    + MinCheckInterval + " to " + MaxCheckInterval);

        // Set the offline check interval for offline passthru servers

        passthruServers = new PassthruServers(this.offlineCheckInterval);

        // DEBUG/*from w w w.j  a va 2 s.  co m*/

        if (logger.isDebugEnabled())
            logger.debug("Using offline check interval of " + this.offlineCheckInterval + " seconds");
    } else {
        // Create the passthru server list with the default offline check interval

        passthruServers = new PassthruServers();
    }

    // Propagate the debug setting

    if (logger.isDebugEnabled())
        passthruServers.setDebug(true);

    // Check if the session timeout has been specified

    if (this.timeout != null) {

        // Range check the timeout

        if (this.timeout < MinSessionTmo || this.timeout > MaxSessionTmo)
            throw new InvalidConfigurationException(
                    "Invalid session timeout, valid range is " + MinSessionTmo + " to " + MaxSessionTmo);

        // Set the session timeout for connecting to an authentication server

        passthruServers.setConnectionTimeout(this.timeout);
    }

    passthruServers.setNullDomainUseAnyServer(this.nullDomainUseAnyServer);

    // Check if a server name has been specified

    String srvList = null;
    if (localServer) {
        try {
            // Get the list of local network addresses

            InetAddress[] localAddrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());

            // Build the list of local addresses

            if (localAddrs != null && localAddrs.length > 0) {
                StringBuilder addrStr = new StringBuilder();

                for (InetAddress curAddr : localAddrs) {
                    if (curAddr.isLoopbackAddress() == false) {
                        addrStr.append(curAddr.getHostAddress());
                        addrStr.append(",");
                    }
                }

                if (addrStr.length() > 0)
                    addrStr.setLength(addrStr.length() - 1);

                // Set the server list using the local address list

                srvList = addrStr.toString();
            } else
                throw new AlfrescoRuntimeException("No local server address(es)");
        } catch (UnknownHostException ex) {
            throw new AlfrescoRuntimeException("Failed to get local address list");
        }
    }

    if (this.server != null && this.server.length() > 0) {

        // Check if the server name was already set

        if (srvList != null)
            throw new AlfrescoRuntimeException("Set passthru server via local server or specify name");

        // Get the passthru authenticator server name

        srvList = this.server;
    }

    // If the passthru server name has been set initialize the passthru connection

    if (srvList != null) {
        // Initialize using a list of server names/addresses

        passthruServers.setServerList(srvList);
    } else {

        // Get the domain/workgroup name

        String domainName = null;

        // Check if a domain name has been specified

        if (this.domain != null && this.domain.length() > 0) {

            // Check if the authentication server has already been set, ie. server name was also specified

            if (srvList != null)
                throw new AlfrescoRuntimeException("Specify server or domain name for passthru authentication");

            domainName = this.domain;
        }

        // If the domain name has been set initialize the passthru connection

        if (domainName != null) {
            try {
                // Initialize using the domain

                passthruServers.setDomain(domainName);
            } catch (IOException ex) {
                throw new AlfrescoRuntimeException("Error setting passthru domain, " + ex.getMessage());
            }
        }
    }

    // Check if we have an authentication server

    if (passthruServers.getTotalServerCount() == 0)
        throw new AlfrescoRuntimeException("No valid authentication servers found for passthru");
}

From source file:cx.fbn.nevernote.threads.SyncRunner.java

@Override
public void run() {
    errorSharedNotebooks = new ArrayList<String>();
    errorSharedNotebooksIgnored = new HashMap<String, String>();
    try {//from   w ww .j  a va  2  s.  co m
        logger.log(logger.EXTREME, "Starting thread");
        conn = new DatabaseConnection(logger, dburl, indexUrl, resourceUrl, behaviorUrl, dbuid, dbpswd, dbcpswd,
                200);
        while (keepRunning) {
            logger.log(logger.EXTREME, "Blocking until work is found");
            String work = workQueue.take();
            logger.log(logger.LOW,
                    "Dirty Notes Before Sync: " + new Integer(conn.getNoteTable().getDirtyCount()).toString());
            logger.log(logger.EXTREME, "Work found: " + work);
            if (work.equalsIgnoreCase("stop")) {
                idle = false;
                return;
            }
            conn.getNoteTable().dumpDirtyNotes(); // Debugging statement
            idle = false;
            error = false;
            if (syncNeeded) {
                logger.log(logger.EXTREME, "SyncNeeded is true");
                refreshNeeded = false;
                sequenceDate = conn.getSyncTable().getLastSequenceDate();
                updateSequenceNumber = conn.getSyncTable().getUpdateSequenceNumber();
                try {
                    logger.log(logger.EXTREME, "Beginning sync");
                    evernoteSync(localNoteStore);
                    logger.log(logger.EXTREME, "Sync finished");
                } catch (UnknownHostException e) {
                    status.message.emit(e.getMessage());
                }
            }
            idle = true;
            logger.log(logger.EXTREME, "Signaling refresh finished.  refreshNeeded=" + refreshNeeded);
            syncSignal.finished.emit(refreshNeeded);
            if (error) {
                syncSignal.errorDisconnect.emit();
                status.message.emit(tr("Error synchronizing - see log for details."));
            }
            logger.log(logger.LOW,
                    "Dirty Notes After Sync: " + new Integer(conn.getNoteTable().getDirtyCount()).toString());
            conn.getNoteTable().dumpDirtyNotes();
            logger.log(logger.LOW, "---");
        }
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    conn.dbShutdown();
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method creates the T.I.M results file for the a specific
 * test case.//from ww w  .  j a v a2  s .c o m
 */
private void generateResults(TSDocument doc) {
    String fileName = doc.getLogFileName();
    int index = fileName.lastIndexOf("_ss.log");
    String timFileName = fileName.substring(0, index) + "_ss.res";
    File tim = new File(timFileName);
    if (!tim.exists()) {
        Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
        Properties dut = SystemSettings.getSettings("DUT");
        try {
            FileOutputStream output = null;
            if (tim.createNewFile()) {
                output = new FileOutputStream(tim);
            } else {
                output = new FileOutputStream((timFileName + "_" + System.currentTimeMillis()));
            }

            String testerName = platform.getProperty(SettingConstants.TESTER_NAME);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date stop = new Date();
            String cw = platform.getProperty(SettingConstants.CW_NUMBER);
            if (!cw.startsWith("CW"))
                cw = "CW" + cw;
            String result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                    + "<res-document xmlns=\"http://cablelabs.com/TEPResultDocument\" version=\"1.0\">\n\t"
                    + "<execution method=\"automatic\" start=\"" + sdf.format(doc.getStart()) + "\" stop=\""
                    + sdf.format(stop) + "\" />\n\t" + "<tester username=\"" + testerName + "\" />\n\t"
                    + "<certwave name=\"" + cw + "\" />\n\t" + "<test-result type=\""
                    + platform.getProperty(SettingConstants.DUT_SUBGROUP) + "\" name=\"" + doc.getNumber()
                    + "\"\n\tproduct=\"" + dut.getProperty(SettingConstants.DUT_VENDOR) + "\" result=\""
                    + ((testPassed == null || testPassed) ? "PASS" : "FAIL") + "\"\n\tunit=\""
                    + dut.getProperty(SettingConstants.PRODUCT_UNIT) + "\"/>\n" + "</res-document>";
            if (output != null) {
                output.write(result.getBytes());
                output.close();
            }
            //            else 
            //               logger.fatal(PC2LogCategory.Parser, subCat,
            //                     "Couldn't write TIM file! Writing to log file for preservation!\n" + result);
        } catch (IOException ioe) {
            logger.error(PC2LogCategory.Parser, subCat, "Could not create new TIM file[" + timFileName + "].");
        }

        String tftpIP = platform.getProperty(SettingConstants.TFTP_SERVER_IP);
        String tftpPort = platform.getProperty(SettingConstants.TFTP_SERVER_PORT);

        if (tftpIP != null && tftpPort != null) {
            boolean recProv = SystemSettings
                    .resolveBooleanSetting(platform.getProperty(SettingConstants.RECORD_PROVISIONING_FILE));
            if (recProv && dut != null)
                try {
                    RecordProvFileListener rpfl = new RecordProvFileListener();
                    boolean success = rpfl.run();
                    String provFile = rpfl.getValue();
                    if (success) {

                        int port = Integer.parseInt(tftpPort);
                        if (port > 0 && port <= 65535) {

                            // Next make sure the TFTP Server IP is not set to 0.0.0.0
                            if (tftpIP.equals("0.0.0.0")) {
                                logger.warn(PC2LogCategory.PCSim2, subCat,
                                        "The TFTP Server IP setting in the platform file is not valid. Ending auto generate operation.");
                            } else {
                                // Next we need to TFTP the file from the server
                                TFTPClient client = new TFTPClient();
                                int dirIndex = fileName.lastIndexOf("/", index);
                                File dir = new File(fileName.substring(0, dirIndex) + PROV_FILE_DIRECTORY);
                                if (dir.exists() && !dir.isDirectory()) {
                                    logger.error(PC2LogCategory.PCSim2, subCat, "The path " + dir.getPath()
                                            + " is not a directory. Terminating the recording of the provisioning file.");
                                }
                                File binFile = new File(fileName.substring(0, dirIndex + 1)
                                        + PROV_FILE_DIRECTORY + File.separator
                                        + fileName.substring(dirIndex + 1, index) + "_prov.bin");
                                boolean exists = false;
                                if (!binFile.exists())
                                    exists = binFile.createNewFile();
                                if (exists && binFile.canWrite()) {
                                    FileOutputStream ostrm = new FileOutputStream(binFile);
                                    //InetAddress ia = InetAddress.getByName("10.4.1.37");
                                    client.open(); // client.open(20003, ia);
                                    client.receiveFile(provFile, TFTP.BINARY_MODE, ostrm, tftpIP, port);
                                    client.close();
                                    logger.info(PC2LogCategory.PCSim2, subCat,
                                            "TFTP of the record provisioning file is complete.");
                                } else {
                                    logger.warn(PC2LogCategory.PCSim2, subCat,
                                            "The system could not TFTP the provisioning file because TFTP address is "
                                                    + tftpIP + ".");
                                }
                            }
                        } else {
                            logger.warn(PC2LogCategory.PCSim2, subCat,
                                    "Recording of the provisioning file is terminating because the port(" + port
                                            + ") is less than 0 or greater than 65535.");
                        }
                    } else {
                        logger.warn(PC2LogCategory.PCSim2, subCat,
                                "Recording of the provisioning file is terminating because PACT returned an error string of \""
                                        + provFile + "\".");
                    }
                } catch (NumberFormatException nfe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "TFTP Server Port setting doesn't appear to be a number.");
                } catch (UnknownHostException uhe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + uhe.getMessage() + "\n" + uhe.getStackTrace());
                } catch (IOException ioe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + ioe.getMessage() + "\n" + ioe.getStackTrace());
                }
        }
    }
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method determines if the provisioning file used to conduct a test needs to
 * be generated from one of the templates prior to starting the test.
 * @return - the MAC address used for the name of the file
 */// ww  w .  j a  v  a 2  s .  c  o  m
private String autoGenerate(ProvisioningData pd) {
    Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
    Properties dut = SystemSettings.getSettings(SettingConstants.DUT);
    if (pd != null && platform != null && dut != null) {
        String pcscfLabel = dut.getProperty(SettingConstants.PCSCF);
        String macAddr = dut.getProperty(SettingConstants.MAC_ADDRESS);
        String tftpIP = platform.getProperty(SettingConstants.TFTP_SERVER_IP);
        String tftpPort = platform.getProperty(SettingConstants.TFTP_SERVER_PORT);
        String phone1 = dut.getProperty(SettingConstants.PHONE_NUMBER_1);
        String phone2 = dut.getProperty(SettingConstants.PHONE_NUMBER_2);
        String cw = platform.getProperty(SettingConstants.CW_NUMBER);
        if (macAddr != null && pcscfLabel != null && tftpIP != null && tftpPort != null && cw != null) {
            // First see if we have already issued a generated file.
            if (!provDB.issued(macAddr, pd)) {
                // Next verify the port is not set to zero
                try {
                    int port = Integer.parseInt(tftpPort);
                    if (port > 0 && port <= 65535) {

                        // Next make sure the TFTP Server IP is not set to 0.0.0.0
                        if (tftpIP.equals("0.0.0.0")) {
                            logger.warn(PC2LogCategory.PCSim2, subCat,
                                    "The TFTP Server IP setting in the platform file is not valid. Ending auto generate operation.");
                            return null;
                        }

                        File input = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                + SettingConstants.CW + cw + File.separator + pd.getProvFileName());
                        if (input != null) {
                            ProvGen pg = new ProvGen(input);
                            if (phone1 != null)
                                pg.changePhoneNum(SettingConstants.AUTO_GENERATE_PHONE_NUMBER_1, phone1);
                            if (phone2 != null)
                                pg.changePhoneNum(SettingConstants.AUTO_GENERATE_PHONE_NUMBER_2, phone2);
                            Properties pcscf = SystemSettings.getSettings(pcscfLabel);
                            if (pcscf != null) {
                                String pcscfIP = pcscf.getProperty(SettingConstants.IP);
                                if (pcscfIP != null)
                                    pg.changePCSCF(pcscfIP);
                            }
                            String newFileName = macAddr + ".bin";
                            if (pg.output(SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                    + SettingConstants.CW + cw + File.separator + newFileName)) {
                                // Test system
                                //File output = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + newFileName);
                                //File pact = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + "chinmaya_base_ph1_pcscf.bin");
                                //pg.compare(pact, output);
                                // Create a data entry of the issued event
                                //ProvisioningData issuePD = new ProvisioningData(macAddr, pd.getPolicyFileName(), newFileName);
                                logger.info(PC2LogCategory.PCSim2, subCat,
                                        "Beginning to TFTP the new provisioning file.");
                                provDB.setIssuedData(macAddr, pd);

                                // Next we need to TFTP the file to the server
                                TFTPClient client = new TFTPClient();
                                File binFile = new File(
                                        SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                                + SettingConstants.CW + cw + File.separator + newFileName);
                                if (binFile.isFile() && binFile.canRead()) {
                                    FileInputStream istrm = new FileInputStream(binFile);
                                    //InetAddress ia = InetAddress.getByName("10.4.1.37");
                                    client.open(); // client.open(20003, ia);
                                    client.sendFile(newFileName, TFTP.BINARY_MODE, istrm, tftpIP, port);
                                    client.close();
                                    logger.info(PC2LogCategory.PCSim2, subCat,
                                            "TFTP of the new provisioning file is complete.");
                                    return macAddr;
                                } else {
                                    logger.warn(PC2LogCategory.PCSim2, subCat,
                                            "The " + macAddr + ".bin doesn't appear in the "
                                                    + SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                                    + SettingConstants.CW + cw
                                                    + " Ending auto generate operation.");
                                }
                            } else {
                                logger.error(PC2LogCategory.PCSim2, subCat,
                                        "PCSim2 could not locate provisioning template file["
                                                + input.getAbsolutePath() + "].");
                            }
                        }
                        //                     else {
                        //                        logger.info(PC2LogCategory.PCSim2, subCat, "Auto provisioning is terminating because the input directory is null.");
                        //                     }
                    } else {
                        logger.info(PC2LogCategory.PCSim2, subCat,
                                "Auto provisioning is terminating because the port(" + port
                                        + ") is less than 0 or greater than 65535.");
                    }
                } catch (NumberFormatException nfe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "TFTP Server Port setting doesn't appear to be a number.");
                } catch (UnknownHostException uhe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + uhe.getMessage() + "\n" + uhe.getStackTrace());
                } catch (IOException ioe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + ioe.getMessage() + "\n" + ioe.getStackTrace());
                }
            } else {
                logger.info(PC2LogCategory.PCSim2, subCat,
                        "Auto provisioning detected the same same provisioning template is already in use, skipping operation.");

            }
        } else {
            logger.info(PC2LogCategory.PCSim2, subCat,
                    "Auto provisioning is stopping because one of the values is null.\n" + "macAddr=" + macAddr
                            + " pcscfLabel=" + pcscfLabel + " tftpIP=" + tftpIP + " tftpPort=" + tftpPort);
        }
    } else {
        if (pd != null)
            logger.info(PC2LogCategory.PCSim2, subCat,
                    "The provisioning data is null, terminating processing.");
        if (platform != null)
            logger.info(PC2LogCategory.PCSim2, subCat,
                    "The Platform settings is null, terminating processing.");
        if (dut != null)
            logger.info(PC2LogCategory.PCSim2, subCat, "The DUT settings is null, terminating processing.");
    }

    return null;
}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStoreClient.java

@Override
public OpenTxnsResponse openTxns(String user, int numTxns) throws TException {
    String hostname = null;// w  w  w  .ja  v a  2  s.  c  om
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LOG.error("Unable to resolve my host name " + e.getMessage());
        throw new RuntimeException(e);
    }
    return client.open_txns(new OpenTxnRequest(numTxns, user, hostname));
}

From source file:org.apache.synapse.startup.quartz.SimpleQuartz.java

public void init(SynapseEnvironment synapseEnvironment) {

    if (taskDescription == null) {
        handleException("Error while initializing the startup. TaskDescription is null.");
    }//from w  ww  .  j  a  v a2  s  . c om

    taskManager = synapseEnvironment.getTaskManager();

    if (!taskManager.isInitialized()) {
        log.warn("SynapseTaskManager is not properly initialized. Initializing now with "
                + "default parameters.");
        taskManager.init(null, null);
    }

    TaskDescriptionRepository repository = taskManager.getTaskDescriptionRepository();

    if (repository == null) {
        handleException("Task Description Repository cannot be found");
        return;
    }

    repository.addTaskDescription(taskDescription);

    // this server name given by system property SynapseServerName
    // otherwise take host-name
    // else assume localhost
    String thisServerName = synapseEnvironment.getServerContextInformation().getServerConfigurationInformation()
            .getServerName();
    if (thisServerName == null || thisServerName.equals("")) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            thisServerName = address.getHostName();

        } catch (UnknownHostException e) {
            log.warn("Could not get the host name", e);
        }

        if (thisServerName == null || thisServerName.equals("")) {
            thisServerName = "localhost";
        }
    }
    log.debug("Synapse server name : " + thisServerName);

    // start proxy service if either,
    // pinned server name list is empty
    // or pinned server list has this server name
    List pinnedServers = taskDescription.getPinnedServers();
    if (pinnedServers != null && !pinnedServers.isEmpty()) {
        if (!pinnedServers.contains(thisServerName)) {
            log.info("Server name not in pinned servers list. Not starting Task : " + getName());
            return;
        }
    }

    try {
        task = (Task) getClass().getClassLoader().loadClass(taskDescription.getTaskClass()).newInstance();
    } catch (Exception e) {
        handleException("Cannot instantiate task : " + taskDescription.getTaskClass(), e);
    }

    Set properties = taskDescription.getProperties();
    for (Object property : properties) {
        OMElement prop = (OMElement) property;
        log.debug("Found Property : " + prop.toString());
        PropertyHelper.setStaticProperty(prop, task);
    }

    if (task instanceof ManagedLifecycle) {
        ((ManagedLifecycle) task).init(synapseEnvironment);
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put(SimpleQuartzJob.SYNAPSE_ENVIRONMENT, synapseEnvironment);

    try {

        TaskScheduler taskScheduler = taskManager.getTaskScheduler();
        if (taskScheduler != null) {
            if (!taskScheduler.isInitialized()) {
                taskScheduler.init(synapseEnvironment.getSynapseConfiguration().getProperties());
            }
            taskScheduler.scheduleTask(taskDescription, map, SimpleQuartzJob.class, task);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("TaskScheduler cannot be found for :" + TaskConstants.TASK_SCHEDULER + " , "
                        + "therefore ignore scheduling of Task  " + taskDescription);
            }
        }

    } catch (Exception e) {
        String msg = "Error starting up Scheduler : " + e.getMessage();
        log.fatal(msg, e);
        throw new SynapseException(msg, e);
    }

}

From source file:com.vangent.hieos.logbrowser.servlets.AuthenticationServlet.java

/**
 * //w  w  w . j av a  2s. c o m
 *  Entry point of the servlet
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("text/xml");
    HttpSession session = req.getSession(true);
    String passwordInput = req.getParameter("password");
    String newPassword = req.getParameter("chgPassword");
    String getIsAdmin = req.getParameter("isAdmin");
    String logout = req.getParameter("logout");
    String ipFrom = req.getRemoteAddr();
    String company = null;
    try {
        InetAddress address = InetAddress.getByName(ipFrom);
        if (address instanceof Inet6Address) {
            if (address.isLoopbackAddress()) {
                ipFrom = "127.0.0.1";
            } else {
                ipFrom = "null";
            }
        }
    } catch (UnknownHostException e) {
    }

    if (ipFrom != null && !ipFrom.equals("null")) {
        Log log = new Log();
        try {
            PreparedStatement selectCompanyName = null;
            Connection con = log.getConnection();
            selectCompanyName = con.prepareStatement("SELECT company_name,email FROM ip where ip = ? ; ");
            selectCompanyName.setString(1, ipFrom);
            ResultSet result = selectCompanyName.executeQuery();
            if (result.next()) {
                company = result.getString(1).replaceAll("'", "&quot;");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (LoggerException e) {
            e.printStackTrace();
        } finally {
            try {
                log.closeConnection();
            } catch (LoggerException ex) {
                Logger.getLogger(AuthenticationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    String pageNumber = (String) session.getAttribute("page");
    String numberResultsByPage = (String) session.getAttribute("numberResultsByPage");
    session.setAttribute("isAdmin", true); // BHT (HACK).

    // DISABLED (BHT)
    // readFile();
    if (passwordInput != null) {
        try {
            if (passwordRead.equals(passwordInput)) {
                session.setAttribute("isAdmin", true);
                if (newPassword != null) {
                    FileWriter fstream;
                    try {
                        fstream = new FileWriter(passwordFile);
                        BufferedWriter out = new BufferedWriter(fstream);
                        out.write(newPassword);
                        out.close();
                        res.getWriter()
                                .write("<response isChanged='true' isAuthenticated='true' page ='" + pageNumber
                                        + "' numberResultByPage='" + numberResultsByPage + "'></response>");

                    } catch (IOException e) {
                        try {
                            res.getWriter().write("<response isChanged='false' page ='" + pageNumber
                                    + "' numberResultByPage='" + numberResultsByPage + "' ip='" + ipFrom + "' +"
                                    + " company='" + company + "' > " + e.getMessage() + "</response>");
                        } catch (IOException e1) {
                        }
                    }

                } else {
                    res.getWriter().write("<response isAuthenticated='true' page ='" + pageNumber
                            + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                }
            } else {
                res.getWriter().write("<response isAuthenticated='false' ip='" + ipFrom + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (Exception e) {
        }
    } else if (getIsAdmin != null && getIsAdmin.equals("get")) {
        try {
            Boolean isAuthenticated = (Boolean) session.getAttribute("isAdmin");
            String sysType = (String) session.getAttribute("systemType");

            if (sysType == null) {
                sysType = "new";
            }

            if (isAuthenticated != null && isAuthenticated.booleanValue()) {
                res.getWriter().write("<response isAuthenticated='true' systemType='" + sysType + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                /*} else if (authorizedIPs.contains(ipFrom)) {
                res.getWriter().write(
                "<response isAuthenticated='true'" + " page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                session.setAttribute("isAdmin", true);
                }*/
            } else {
                res.getWriter()
                        .write("<response isAuthenticated='false' ip='" + ipFrom + "' systemType ='" + sysType
                                + "' company    ='" + company + "' page       ='" + pageNumber
                                + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (IOException e) {
        }
    } else if (logout != null && logout.equals("yes")) {
        session.invalidate();
        try {
            res.getWriter().write("<response/>");
        } catch (IOException e) {
        }
    }
}

From source file:com.clustercontrol.repository.factory.NodeSearcher.java

public List<NodeInfoDeviceSearch> searchNode(String ownerRoleId, String ipAddrFrom, String ipAddrTo, int port,
        String community, int version, String facilityID, String securityLevel, String user, String authPass,
        String privPass, String authProtocol, String privProtocol)
        throws HinemosUnknown, FacilityDuplicate, InvalidSetting {

    long startTime = HinemosTime.currentTimeMillis();
    // ?(60)???????
    int maxMsec = HinemosPropertyUtil
            .getHinemosPropertyNum("repository.node.search.timeout", Long.valueOf(50 * 1000)).intValue();
    List<NodeInfoDeviceSearch> nodeList = new ArrayList<NodeInfoDeviceSearch>();

    if (duplicateExec.tryAcquire()) {
        try {//from   ww w  .  j a v  a 2  s.c om
            String errMsg = MessageConstant.MESSAGE_PLEASE_SET_IPADDR_CORRECT_FORMAT.getMessage();

            //?
            if (ipAddrFrom == null || ipAddrFrom.equals("") || ipAddrTo == null || ipAddrTo.equals("")) {
                throw new HinemosUnknown(MessageConstant.MESSAGE_PLEASE_SET_SEARCH_IPADDR.getMessage());
            } else if (version == SnmpVersionConstant.TYPE_V3
                    && securityLevel.equals(SnmpSecurityLevelConstant.NOAUTH_NOPRIV) == false) {
                if (user == null || user.equals("")) {
                    throw new HinemosUnknown(MessageConstant.MESSAGE_PLEASE_SET_USER_NAME.getMessage());
                } else if (authPass == null || authPass.equals("")) {
                    throw new HinemosUnknown(
                            MessageConstant.MESSAGE_PLEASE_SET_AUTHPASS_8CHARA_MINIMUM.getMessage());
                } else if (securityLevel.equals(SnmpSecurityLevelConstant.AUTH_PRIV)) {
                    if (privPass == null || privPass.equals("")) {
                        throw new HinemosUnknown(
                                MessageConstant.MESSAGE_PLEASE_SET_PRIVPASS_8CHARA_MINIMUM.getMessage());
                    }
                }
            }

            List<String> ipAddressList = null;

            // IP?
            InetAddress addressFrom;
            InetAddress addressTo;
            try {
                addressFrom = InetAddress.getByName(ipAddrFrom);
                addressTo = InetAddress.getByName(ipAddrTo);

                if (addressFrom instanceof Inet4Address && addressTo instanceof Inet4Address) {
                    //IPv4?????String?
                    if (!ipAddrFrom.matches(".{1,3}?\\..{1,3}?\\..{1,3}?\\..{1,3}?")) {
                        m_log.info(errMsg);
                        throw new HinemosUnknown(errMsg);
                    }
                    ipAddressList = RepositoryUtil.getIpList(ipAddrFrom, ipAddrTo, 4);
                } else if (addressFrom instanceof Inet6Address && addressTo instanceof Inet6Address) {
                    //IPv6????String???
                    ipAddressList = RepositoryUtil.getIpList(ipAddrFrom, ipAddrTo, 6);
                } else {
                    m_log.info(errMsg);
                    throw new HinemosUnknown(errMsg);
                }
            } catch (UnknownHostException e) {
                m_log.warn(errMsg);
                throw new HinemosUnknown(errMsg);
            }

            if (m_log.isDebugEnabled()) {
                StringBuilder str = new StringBuilder();
                for (String ipAddress : ipAddressList) {
                    if (str.length() != 0) {
                        str.append(", ");
                    }
                    str.append(ipAddress);
                }
                m_log.debug("ipAddress=" + str);
            }

            List<NodeInfoDeviceSearch> searchList = new ArrayList<>();
            try {
                //?
                //256?????
                if (ipAddressList.size() > HinemosPropertyUtil.getHinemosPropertyNum(MaxSearchNodeKey,
                        Long.valueOf(256))) {
                    m_log.info(MessageConstant.MESSAGE_EXCEED_LIMIT_NUMBER_256NODES.getMessage());
                    throw new HinemosUnknown(MessageConstant.MESSAGE_EXCEED_LIMIT_NUMBER_256NODES.getMessage());
                }

                //????
                //delay????????????(60??????)
                List<Future<NodeInfoDeviceSearch>> list = new ArrayList<>();
                for (String ipAddress : ipAddressList) {
                    if (list.size() > 0) {
                        Thread.sleep(HinemosPropertyUtil.getHinemosPropertyNum("repository.node.search.delay",
                                Long.valueOf(10)));
                    }
                    try {
                        InetAddress address = InetAddress.getByName(ipAddress);
                        List<String> facilityList = new RepositoryControllerBean()
                                .getFacilityIdByIpAddress(address);
                        if (facilityList != null && 0 < facilityList.size()) {
                            //??IP????
                            m_log.info("ipAddress " + address + " is already registered.");
                            continue;
                        }
                    } catch (UnknownHostException e) {
                        m_log.warn("UnknownHostException : " + e.getMessage()); // ???????
                        continue;
                    }
                    NodeSearchTask task = new NodeSearchTask(ipAddress, port, community, version, facilityID,
                            securityLevel, user, authPass, privPass, authProtocol, privProtocol);
                    list.add(_executorService.submit(task));
                }

                for (Future<NodeInfoDeviceSearch> future : list) {
                    if (future != null) {
                        try {
                            // SNMP??5?????????get??????
                            searchList.add(future.get(maxMsec, TimeUnit.MILLISECONDS));
                        } catch (TimeoutException e) {
                            m_log.warn("searchNode : " + e.getClass().getName() + ", " + e.getMessage());
                        }
                    }
                }
            } catch (InterruptedException e) {
                m_log.warn("searchNode : " + e.getClass().getName() + ", " + e.getMessage(), e);
                throw new HinemosUnknown(e.getMessage(), e);
            } catch (ExecutionException e) {
                m_log.warn("searchNode : " + e.getClass().getName() + ", " + e.getMessage(), e);
                throw new HinemosUnknown(e.getMessage(), e);
            }

            //
            RepositoryControllerBean controller = new RepositoryControllerBean();

            boolean commitFlag = false;
            for (NodeInfoDeviceSearch searchInfo : searchList) {
                try {
                    if (searchInfo == null) {
                        m_log.warn("searchInfo is null");
                        continue;
                    }
                    nodeList.add(searchInfo);
                    NodeInfo nodeInfo = searchInfo.getNodeInfo();
                    nodeInfo.setOwnerRoleId(ownerRoleId);
                    m_log.info("nodeInfo " + nodeInfo);
                    if (searchInfo.getErrorMessage() != null) {
                        continue;
                    }

                    //?
                    long msec = HinemosTime.currentTimeMillis() - startTime;
                    if (msec > maxMsec) {
                        m_log.info(MessageConstant.MESSAGE_TIME_OUT.getMessage() + " msec=" + msec);
                        throw new HinemosUnknown(MessageConstant.MESSAGE_TIME_OUT.getMessage());
                    }
                    try {
                        //????????
                        controller.addNodeWithoutRefresh(nodeInfo);
                        commitFlag = true;
                    } catch (FacilityDuplicate | InvalidSetting | HinemosUnknown e) {
                        String errorMessage = "" + e.getMessage();
                        searchInfo.setErrorMessage(errorMessage);
                    } finally {
                    }
                } catch (Exception e) {
                    m_log.warn("searchNode : " + e.getClass().getName() + ", " + e.getMessage(), e);
                    throw new HinemosUnknown(e.getMessage());
                }
            }
            if (commitFlag) {
                new FacilityIdCacheInitCallback().postCommit();

                //FacilityTreeCache??????
                JpaTransactionManager jtm = new JpaTransactionManager();
                try {
                    jtm.begin();
                    new FacilityTreeCacheRefreshCallback().postCommit();
                    jtm.commit();
                } catch (Exception e1) {
                    jtm.rollback();
                    throw e1;
                } finally {
                    jtm.close();
                }

                new RepositoryChangedNotificationCallback().postCommit();
            }
        } catch (HinemosUnknown e) {
            throw e;
        } finally {
            m_log.info("node search : " + "ipAddrFrom=" + ipAddrFrom + ", ipAddrTo=" + ipAddrTo + ", time="
                    + (HinemosTime.currentTimeMillis() - startTime) + "ms");
            duplicateExec.release();
        }
    } else {
        m_log.warn("runningCheck is busy !!");
    }

    return nodeList;
}

From source file:org.sakaiproject.antivirus.impl.ClamAVScanner.java

protected void doScan(InputStream in) throws VirusScanIncompleteException, VirusFoundException {
    logger.debug("doingScan!");
    Socket socket = null;/*  w w  w.j a  v a2  s.c  o  m*/
    String virus = null;
    long start = System.currentTimeMillis();
    //this could be a null or zero lenght stream
    if (in == null) {
        return;
    }

    try {
        socket = getClamdSocket();
    } catch (UnknownHostException e) {
        logger.error("could not connect to host for virus check: " + e);
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG);
    }
    if (socket == null || !socket.isConnected()) {
        logger.warn("scan is inclomplete!");
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG);
    }
    BufferedReader reader = null;
    PrintWriter writer = null;
    Socket streamSocket = null;
    boolean virusFound = false;
    try {

        // prepare the reader and writer for the commands
        boolean autoFlush = true;
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"));
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
                autoFlush);
        // write a request for a port to use for streaming out the data to scan
        writer.println("STREAM");

        // parse and get the "stream" port#
        int streamPort = getStreamPortFromAnswer(reader.readLine());

        // get the "stream" socket and the related (buffered) output stream
        streamSocket = new Socket(socket.getInetAddress(), streamPort);
        OutputStream os = streamSocket.getOutputStream();

        // stream out the message to the scanner
        int data;
        // -1 signals the end of the data stream
        while ((data = in.read()) > -1) {
            os.write(data);
        }
        os.flush();
        os.close();
        streamSocket.close();

        String logMessage = "";
        String answer = null;
        for (int i = 0; i < 100; ++i) {
            answer = reader.readLine();
            if (answer != null) {
                answer = answer.trim();

                // if a virus is found the answer will be '... FOUND'
                if (answer.substring(answer.length() - FOUND_STRING.length()).equals(FOUND_STRING)) {
                    virusFound = true;
                    logMessage = answer + " (by virus scanner)";
                    //virus = answer.substring(answer.indexOf(":" + 1));
                    virus = answer.substring(0, answer.indexOf(FOUND_STRING)).trim();
                    logger.debug(logMessage);
                } else {
                    logger.debug("no virus found: " + answer);
                }
            } else {
                break;
            }
        }
        long finish = System.currentTimeMillis();
        logger.debug("Content scanned in " + (finish - start));
    } catch (UnsupportedEncodingException e) {
        logger.error("Exception caught calling CLAMD on " + socket.getInetAddress() + ": " + e.getMessage());
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG, e);
    } catch (IOException e) {
        //we expect a connection reset if we tried to send too much data to clamd
        if ("Connection reset".equals(e.getMessage())) {
            logger.warn("Clamd reset the connection maybe due to the file being too large");
            return;
        }
        logger.error("Exception caught calling CLAMD on " + socket.getInetAddress() + ": " + e.getMessage());
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG, e);

    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        if (writer != null) {
            writer.close();
        }
        if (streamSocket != null) {
            try {
                streamSocket.close();
            } catch (IOException e) {

            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {

            }
        }

    }
    if (virusFound) {
        logger.info("Virus detected!: " + virus);
        throw new VirusFoundException(virus);
    }

}

From source file:org.entrystore.harvesting.oaipmh.jobs.ListRecordsJob.java

/**
 * /*from   w  w  w  . j ava2s .c  o m*/
 * @param out
 * @throws Exception
 */
synchronized public void run(OutputStream out, JobExecutionContext jobContext) throws Exception {
    JobDataMap dataMap = jobContext.getJobDetail().getJobDataMap();
    RepositoryManagerImpl rm = (RepositoryManagerImpl) dataMap.get("rm");
    ContextManager cm = rm.getContextManager();
    final PrincipalManager pm = rm.getPrincipalManager();

    initXpath();

    URI contextURI = (URI) dataMap.get("contextURI");
    String contextId = contextURI.toString().substring(contextURI.toString().lastIndexOf("/") + 1);
    final Context context = cm.getContext(contextId);
    final String metadataType = dataMap.getString("metadataType");
    final String target = dataMap.getString("target");
    String from = dataMap.getString("from");
    String until = dataMap.getString("until");
    String set = dataMap.getString("set");
    replaceMetadata = "replace"
            .equalsIgnoreCase(rm.getConfiguration().getString(Settings.HARVESTER_OAI_METADATA_POLICY, "skip"));
    boolean fromAutoDetect = "on"
            .equalsIgnoreCase(rm.getConfiguration().getString(Settings.HARVESTER_OAI_FROM_AUTO_DETECT, "on"));

    if (from == null && fromAutoDetect) {
        Date latestEntry = null;
        Set<URI> allEntries = context.getEntries();
        for (URI uri : allEntries) {
            Entry entry = context.getByEntryURI(uri);
            if (entry != null && (EntryType.Reference.equals(entry.getEntryType())
                    || EntryType.LinkReference.equals(entry.getEntryType()))) {
                Date cachedDate = entry.getExternalMetadataCacheDate();
                if (cachedDate != null) {
                    if (latestEntry == null || cachedDate.after(latestEntry)) {
                        latestEntry = cachedDate;
                    }
                }
            }
        }
        if (latestEntry != null) {
            from = new SimpleDateFormat("yyyy-MM-dd").format(latestEntry);
        }
    }

    log.info("OAI-PMH metadataType: " + metadataType);
    log.info("OAI-PMH target: " + target);
    log.info("OAI-PMH from: " + from);
    log.info("OAI-PMH until: " + until);
    log.info("OAI-PMH set: " + set);

    // Get the listrecord from the OAI-PMH target
    ListRecords listRecords = null;
    try {
        listRecords = new ListRecords(target, from, until, set, metadataType);
    } catch (UnknownHostException e) {
        // TODO: handle exception write in the RDF tree
        log.info("UnknownHostException since the target is unknown, the havester will be deleted");
        jobContext.getScheduler().interrupt(jobContext.getJobDetail().getName(),
                jobContext.getJobDetail().getGroup());
        return;
    }

    ThreadPoolExecutor exService = null;
    if ("on".equalsIgnoreCase(rm.getConfiguration().getString(Settings.HARVESTER_OAI_MULTITHREADED, "off"))) {
        int cpuCount = Runtime.getRuntime().availableProcessors();
        if (cpuCount == 1) {
            log.info("Multi-threaded harvesting activated, but only one CPU found; continuing single-threaded");
        } else {
            int threadCount = cpuCount + 1;
            log.info("Creating executor for multi-threaded harvesting, using thread pool of " + threadCount
                    + " (available CPUs + 1) threads");
            exService = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount);
        }
    } else {
        log.info("Performing single-threaded harvesting");
    }

    Date before = new Date();
    int j = 0;
    while (listRecords != null) {
        NodeList errors = listRecords.getErrors();
        if (errors != null && errors.getLength() > 0) {
            log.error("Found errors");
            int length = errors.getLength();
            for (int i = 0; i < length; ++i) {
                Node item = errors.item(i);
                System.out.println(item);
            }
            log.error("Error record: " + listRecords.toString());
            break;
        }

        //out.write(listRecords.toString().getBytes()); 

        // Get the <Root>-element
        final Element el = listRecords.getDocument().getDocumentElement();
        if (el.getElementsByTagName("ListRecords").getLength() == 0) {
            log.error("No ListRecords");
            throw new Exception("No ListRecords");
        }

        // Get the <ListRecords> element
        Element listRecordsElement = (Element) el.getElementsByTagName("ListRecords").item(0);
        NodeList recordList = listRecordsElement.getElementsByTagName("record");
        // old NodeList recordList = getRecords(listRecordsElement);

        // Create entries from the XML
        for (int i = 0; i < recordList.getLength(); i++) {
            final Element recordElement = (Element) recordList.item(i).cloneNode(true);

            if (exService == null) {
                try {
                    createEntry(context, recordElement, target, metadataType);
                } catch (XPathExpressionException e) {
                    log.error(e.getMessage());
                }
            } else {
                exService.execute(new Runnable() {
                    public void run() {
                        try {
                            pm.setAuthenticatedUserURI(pm.getAdminUser().getURI());
                            createEntry(context, recordElement, target, metadataType);
                        } catch (XPathExpressionException e) {
                            log.error(e.getMessage());
                        }
                    }
                });
                // not sure whether the following is necessary
                while (exService.getQueue().size() > 250) {
                    log.info("Waiting before submitting additional Runnables, current queue size is "
                            + exService.getQueue().size());
                    Thread.sleep(50);
                    log.info("Continuing, the current queue size is " + exService.getQueue().size());
                }
            }
            log.debug("total index: " + j++);
        }

        // Check if there is any resumption token
        String resumptionToken = listRecords.getResumptionToken();
        if (resumptionToken == null || resumptionToken.length() == 0) {
            listRecords = null;
        } else {
            log.info("Got resumption token");
            listRecords = new ListRecords(target, resumptionToken);
        }
    }

    if (exService != null) {
        while (exService.getQueue().size() > 0) {
            log.info("Runnables left in queue: " + exService.getQueue().size() + ", waiting");
            Thread.sleep(2000);
        }
        exService.shutdown();
    }

    log.info("OAI-PMH harvester done with execution");
    long diff = new Date().getTime() - before.getTime();
    if (j > 0) {
        log.info("Harvesting of " + j + " records took " + diff + " ms (average of " + diff / j
                + " ms per record)");
    }
}