Esempio n. 1
1
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // used until/unless gui is created
    consoleHandler = new FancyConsoleHandler();
    // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);

    // todo: why is this here?
    Runtime.getRuntime().addShutdownHook(new ServerShutdownThread());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));
  }
Esempio n. 2
1
  /**
   * Load a system library from a stream. Copies the library to a temp file and loads from there.
   *
   * @param libname name of the library (just used in constructing the library name)
   * @param is InputStream pointing to the library
   */
  private void loadLibraryFromStream(String libname, InputStream is) {
    try {
      File tempfile = createTempFile(libname);
      OutputStream os = new FileOutputStream(tempfile);

      logger.debug("tempfile.getPath() = " + tempfile.getPath());

      long savedTime = System.currentTimeMillis();

      // Leo says 8k block size is STANDARD ;)
      byte buf[] = new byte[8192];
      int len;
      while ((len = is.read(buf)) > 0) {
        os.write(buf, 0, len);
      }

      os.flush();
      InputStream lock = new FileInputStream(tempfile);
      os.close();

      double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;
      logger.debug("Copying took " + seconds + " seconds.");

      logger.debug("Loading library from " + tempfile.getPath() + ".");
      System.load(tempfile.getPath());

      lock.close();
    } catch (IOException io) {
      logger.error("Could not create the temp file: " + io.toString() + ".\n");
    } catch (UnsatisfiedLinkError ule) {
      logger.error("Couldn't load copied link file: " + ule.toString() + ".\n");
      throw ule;
    }
  }
Esempio n. 3
0
 /** Generate a local password and save it in the local-password file. */
 public void postConstruct() {
   logger.fine("Generating local password");
   SecureRandom random = new SecureRandom();
   byte[] pwd = new byte[PASSWORD_BYTES];
   random.nextBytes(pwd);
   password = toHex(pwd);
   File localPasswordFile = new File(env.getConfigDirPath(), LOCAL_PASSWORD_FILE);
   PrintWriter w = null;
   try {
     if (!localPasswordFile.exists()) {
       localPasswordFile.createNewFile();
       /*
        * XXX - There's a security hole here.
        * Between the time the file is created and the permissions
        * are changed to prevent others from opening it, someone
        * else could open it and wait for the data to be written.
        * Java needs the ability to create a file that's readable
        * only by the owner; coming in JDK 7.
        */
       localPasswordFile.setWritable(false, false); // take from all
       localPasswordFile.setWritable(true, true); // owner only
       localPasswordFile.setReadable(false, false); // take from all
       localPasswordFile.setReadable(true, true); // owner only
     }
     w = new PrintWriter(localPasswordFile);
     w.println(password);
   } catch (IOException ex) {
     // ignore errors
     logger.log(Level.FINE, "Exception writing local password file", ex);
   } finally {
     if (w != null) w.close();
   }
 }
Esempio n. 4
0
  public boolean intersects(int x, int y, Rectangle rectangle) {
    try {
      Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1);
      Rectangle right =
          new Rectangle(
              rectangle.getX() + rectangle.getWidth() + 1,
              rectangle.getY(),
              1,
              rectangle.getHeight());
      Rectangle down =
          new Rectangle(
              rectangle.getX(),
              rectangle.getY() + rectangle.getHeight() + 1,
              rectangle.getWidth(),
              1);
      Rectangle left =
          new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight());
      Rectangle rect = blocks[x][y].getRect();

      return (rect.intersects(up)
          || rect.intersects(right)
          || rect.intersects(down)
          || rect.intersects(left));
    } catch (NullPointerException e) {
      logger.log("NullPointerException in World.intersects(int, int, Rectangle)", Level.DEBUG);
      logger.log("Stack:", Level.DEBUG);
      logger.log(e.getMessage(), Level.DEBUG);
    }
    return false;
  }
  /** Implements notification in order to track socket state. */
  @Override
  public synchronized void onSctpNotification(SctpSocket socket, SctpNotification notification) {
    if (logger.isDebugEnabled()) {
      logger.debug("socket=" + socket + "; notification=" + notification);
    }
    switch (notification.sn_type) {
      case SctpNotification.SCTP_ASSOC_CHANGE:
        SctpNotification.AssociationChange assocChange =
            (SctpNotification.AssociationChange) notification;

        switch (assocChange.state) {
          case SctpNotification.AssociationChange.SCTP_COMM_UP:
            if (!assocIsUp) {
              boolean wasReady = isReady();

              assocIsUp = true;
              if (isReady() && !wasReady) notifySctpConnectionReady();
            }
            break;

          case SctpNotification.AssociationChange.SCTP_COMM_LOST:
          case SctpNotification.AssociationChange.SCTP_SHUTDOWN_COMP:
          case SctpNotification.AssociationChange.SCTP_CANT_STR_ASSOC:
            try {
              closeStream();
            } catch (IOException e) {
              logger.error("Error closing SCTP socket", e);
            }
            break;
        }
        break;
    }
  }
Esempio n. 6
0
  public void update(Observable source, Object object) {
    if (source instanceof Users) {
      if (!this.isDisabled()) {
        try {
          Operations.sendUserNamesList(users.getUserNames(), out);
        } catch (IOException io) {
          logger.error("IO Exception", io);
        }
      }
    }

    if (source instanceof Messages) {
      try {
        Operations.sendMessage((MessageType) object, out);
      } catch (IOException io) {
        if (out != null) {
          try {
            out.close();
          } catch (Exception ioe) {
            logger.error("Failed to close the output stream", ioe);
          }
        }

        logger.error("Impossible to send messages", io);
      }
    }
  }
Esempio n. 7
0
  /**
   * Handles a specific <tt>IOException</tt> which was thrown during the execution of {@link
   * #runInConnectThread(DTLSProtocol, TlsPeer, DatagramTransport)} while trying to establish a DTLS
   * connection
   *
   * @param ioe the <tt>IOException</tt> to handle
   * @param msg the human-readable message to log about the specified <tt>ioe</tt>
   * @param i the number of tries remaining after the current one
   * @return <tt>true</tt> if the specified <tt>ioe</tt> was successfully handled; <tt>false</tt>,
   *     otherwise
   */
  private boolean handleRunInConnectThreadException(IOException ioe, String msg, int i) {
    // SrtpControl.start(MediaType) starts its associated TransformEngine.
    // We will use that mediaType to signal the normal stop then as well
    // i.e. we will ignore exception after the procedure to stop this
    // PacketTransformer has begun.
    if (mediaType == null) return false;

    if (ioe instanceof TlsFatalAlert) {
      TlsFatalAlert tfa = (TlsFatalAlert) ioe;
      short alertDescription = tfa.getAlertDescription();

      if (alertDescription == AlertDescription.unexpected_message) {
        msg += " Received fatal unexpected message.";
        if (i == 0
            || !Thread.currentThread().equals(connectThread)
            || connector == null
            || mediaType == null) {
          msg += " Giving up after " + (CONNECT_TRIES - i) + " retries.";
        } else {
          msg += " Will retry.";
          logger.error(msg, ioe);

          return true;
        }
      } else {
        msg += " Received fatal alert " + alertDescription + ".";
      }
    }

    logger.error(msg, ioe);
    return false;
  }
Esempio n. 8
0
  /**
   * When data is available on the socket, this method is called to run the command or throw an
   * error if it can't.
   *
   * @throws SocketServerException
   */
  private void handleClientData() throws SocketServerException {
    try {
      input.setLength(0); // clear

      String res;
      int a;
      // (char) -1 is not equal to -1.
      // ready is checked to ensure the read call doesn't block.
      while ((a = in.read()) != -1 && in.ready()) {
        input.append((char) a);
      }
      String inputString = input.toString();
      Logger.debug("Got data from client: " + inputString);
      try {
        AndroidCommand cmd = getCommand(inputString);
        Logger.debug("Got command of type " + cmd.commandType().toString());
        res = runCommand(cmd);
        Logger.debug("Returning result: " + res);
      } catch (final CommandTypeException e) {
        res = new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()).toString();
      } catch (final JSONException e) {
        res =
            new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, "Error running and parsing command")
                .toString();
      }
      out.write(res);
      out.flush();
    } catch (final IOException e) {
      throw new SocketServerException(
          "Error processing data to/from socket (" + e.toString() + ")");
    }
  }
  protected void load(String filename, InputStream in) {
    Logger.getLogger(getClass()).debug("Starting group in stream " + filename);

    ZipInputStream zipfile = null;
    try {
      zipfile = new ZipInputStream(in);

      fireBeginGroup(filename, -1);

      Logger.getLogger(getClass()).debug("Loading ZipInputStream " + filename);
      load(zipfile);
      Logger.getLogger(getClass()).debug("Loaded ZipInputStream " + filename);

      fireEndGroup(filename);
    } catch (IOException ex) {
      Logger.getLogger(getClass()).error("Cannot load Zip file \"" + filename + "\"", ex);
    } finally {
      if (zipfile != null) {
        try {
          zipfile.close();
        } catch (IOException ex) {
          // Ignore
        }
      }
    }
  }
  protected void load(ZipFile zipfile) throws IOException {
    Enumeration entries = zipfile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) entries.nextElement();

      fireBeginFile(entry.getName());

      Logger.getLogger(getClass())
          .debug("Starting file " + entry.getName() + " (" + entry.getSize() + " bytes)");

      byte[] bytes = null;
      InputStream in = null;
      try {
        in = zipfile.getInputStream(entry);
        bytes = readBytes(in);
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException ex) {
            // Ignore
          }
        }
      }

      Logger.getLogger(getClass())
          .debug("Passing up file " + entry.getName() + " (" + bytes.length + " bytes)");
      getLoader().load(entry.getName(), new ByteArrayInputStream(bytes));

      fireEndFile(entry.getName());
    }
  }
Esempio n. 11
0
  /** Load the configuration file for our server. This method is thread-safe. */
  public static synchronized void load() {
    // # Ensure config file not already loaded...
    if (configLoaded) {
      return;
    }

    // # Read configuration file, and assign it to our configuration JSONObject
    try {
      configuration = (JsonObject) new JsonParser().parse(readFile("config.json").toString());
    } catch (JsonParseException e) {
      // # Someone must have modified (poorly) the JSON configuration file.
      Logger.log("Malformed JSON in the configuration file.", Logger.CRITICAL);
    } catch (FileNotFoundException e) {
      // # Couldn't find the config file, so we write our default one.
      Logger.log(
          "Cannot find the configuration file. Creating default config file.", Logger.CRITICAL);
      configuration = (JsonObject) new JsonParser().parse(create().toString());
    }

    // # Go ahead and assign these values. This is more for developers of SmartSocket than end-user
    // use.
    try {
      Config.autoUpdate = configuration.getAsJsonObject("auto-update");
      Config.crossdomainPolicyFile = configuration.getAsJsonObject("crossdomain-policy-file");
      Config.tcpExtensions = configuration.getAsJsonObject("tcp-extensions");
      Config.udpExtensions = configuration.getAsJsonObject("udp-extensions");
    } catch (Exception e) {
    }

    Logger.log("Configuration loading is complete.", Logger.CRITICAL);
    configLoaded = true;
  }
Esempio n. 12
0
  /**
   * Create a configuration file based on the internally stored configuration.
   *
   * @return The StringBuffer object associated with the internal JSON configuration file.
   */
  private static StringBuffer create() {
    Logger.log("Creating default configuration file 'config.json'...", Logger.CRITICAL);
    StringBuffer fileData = getLocalConfig();

    try {
      JsonObject json = (JsonObject) new JsonParser().parse(fileData.toString());

      // # Remove config version from the output
      // # This config string will be used internally for
      // # tracking versions of cingif files when writing new ones
      // # or receiving new ones.
      json.remove("config-version");

      // # Write configuration file.
      FileOutputStream out = new FileOutputStream("config.json");
      out.write(json.toString().getBytes());
      out.close();

    } catch (JsonParseException e) {
      // # Should never get here because the config file is packaged internaly...
      // # If it fails, probably a developer not formatting the config file properly.
      Logger.log(
          "Compiling and creating the config file failed. Ensure you have properly formatted JSON data before recompiling your extension.",
          Logger.CRITICAL);
    } catch (IOException e) {
      Logger.log("Failed to write the configuration file: " + e.getMessage(), Logger.CRITICAL);
    }

    return fileData;
  }
Esempio n. 13
0
  private void ConnectKnowledgeBaseBtnMouseClicked(
      java.awt.event.MouseEvent evt) { // GEN-FIRST:event_ConnectKnowledgeBaseBtnMouseClicked

    String sPrjFile = ProjectNameTF.getText().trim();
    String sLocationURI = sURI + "Location";

    Collection errors = new ArrayList();
    Date d1 = new Date();
    long l1 = d1.getTime();
    prj = Project.loadProjectFromFile(sPrjFile, errors);
    owlModel = (OWLModel) prj.getKnowledgeBase();

    kb = prj.getKnowledgeBase();
    URI uri = prj.getActiveRootURI();

    Collection colNumberOfInstance = kb.getInstances();
    lNumberOfInstance = colNumberOfInstance.size();

    Date d2 = new Date();
    long l2 = d2.getTime();
    lLoadedTime = (l2 - l1);

    theLogger.info("Connected to MySQL in " + lLoadedTime + " ms");
    theLogger.info("KB has " + lNumberOfInstance + " instances");

    LoggingAreaTA.append("Project has " + lNumberOfInstance + " in total\n");
    LoggingAreaTA.append("Project is loaded in " + lLoadedTime + " ms\n");
  } // GEN-LAST:event_ConnectKnowledgeBaseBtnMouseClicked
Esempio n. 14
0
  private void removeReceiveStream(ReceiveStreamDesc receiveStream, boolean emptyJB) {
    if (receiveStream.format instanceof VideoFormat) {
      rtpConnector.packetBuffer.disable(receiveStream.ssrc);
      emptyPacketBuffer(receiveStream.ssrc);
    }

    if (receiveStream.dataSink != null) {
      try {
        receiveStream.dataSink.stop();
      } catch (IOException e) {
        logger.error("Failed to stop DataSink " + e);
      }

      receiveStream.dataSink.close();
    }

    if (receiveStream.processor != null) {
      receiveStream.processor.stop();
      receiveStream.processor.close();
    }

    DataSource dataSource = receiveStream.receiveStream.getDataSource();
    if (dataSource != null) {
      try {
        dataSource.stop();
      } catch (IOException ioe) {
        logger.warn("Failed to stop DataSource");
      }
      dataSource.disconnect();
    }

    synchronized (receiveStreams) {
      receiveStreams.remove(receiveStream);
    }
  }
Esempio n. 15
0
  public synchronized void messageReceived(int to, Message m) {

    DrainMsg mhMsg = (DrainMsg) m;

    log.debug(
        "incoming: localDest: "
            + to
            + " type:"
            + mhMsg.get_type()
            + " hops:"
            + (16 - mhMsg.get_ttl())
            + " seqNo:"
            + mhMsg.get_seqNo()
            + " source:"
            + mhMsg.get_source()
            + " finalDest:"
            + mhMsg.get_dest());

    // lets assume that the network cannot buffer more than 25 drain msgs from a single source at a
    // time (should be more than reasonable)
    if (seqNos.containsKey(new Integer(mhMsg.get_source()))) {
      int oldSeqNo = ((Integer) seqNos.get(new Integer(mhMsg.get_source()))).intValue();
      int upperBound = mhMsg.get_seqNo() + 25;
      int wrappedUpperBound = 25 - (255 - mhMsg.get_seqNo());
      if ((oldSeqNo >= mhMsg.get_seqNo() && oldSeqNo < upperBound)
          || (oldSeqNo >= 0 && oldSeqNo < wrappedUpperBound)) {
        log.debug(
            "Dropping message from "
                + mhMsg.get_source()
                + " with duplicate seqNo: "
                + mhMsg.get_seqNo());
        return;
      }
    }
    seqNos.put(new Integer(mhMsg.get_source()), new Integer(mhMsg.get_seqNo()));

    if (to != spAddr && to != MoteIF.TOS_BCAST_ADDR && to != TOS_UART_ADDR) {
      log.debug("Dropping message not for me.");
      return;
    }

    HashSet promiscuousSet = (HashSet) idTable.get(new Integer(BCAST_ID));
    HashSet listenerSet = (HashSet) idTable.get(new Integer(mhMsg.get_type()));

    if (listenerSet != null && promiscuousSet != null) {
      listenerSet.addAll(promiscuousSet);
    } else if (listenerSet == null && promiscuousSet != null) {
      listenerSet = promiscuousSet;
    }

    if (listenerSet == null) {
      log.debug("No Listener for type: " + mhMsg.get_type());
      return;
    }

    for (Iterator it = listenerSet.iterator(); it.hasNext(); ) {
      MessageListener ml = (MessageListener) it.next();
      ml.messageReceived(to, mhMsg);
    }
  }
Esempio n. 16
0
 private void handleException(Exception e) {
   if (INTERRUPTED_EXCEPTION_TYPES.contains(e.getClass())) {
     LOG.info("Changes feed was interrupted");
   } else {
     LOG.error("Caught exception while listening to changes feed:", e);
   }
 }
Esempio n. 17
0
  /**
   * Listens on the socket for data, and calls {@link #handleClientData()} when it's available.
   *
   * @throws SocketServerException
   */
  public void listenForever() throws SocketServerException {
    Logger.debug("Appium Socket Server Ready");
    UpdateStrings.loadStringsJson();
    dismissCrashAlerts();
    final TimerTask updateWatchers =
        new TimerTask() {
          @Override
          public void run() {
            try {
              watchers.check();
            } catch (final Exception e) {
            }
          }
        };
    timer.scheduleAtFixedRate(updateWatchers, 100, 100);

    try {
      client = server.accept();
      Logger.debug("Client connected");
      in = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
      out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8"));
      while (keepListening) {
        handleClientData();
      }
      in.close();
      out.close();
      client.close();
      Logger.debug("Closed client connection");
    } catch (final IOException e) {
      throw new SocketServerException("Error when client was trying to connect");
    }
  }
Esempio n. 18
0
    /**
     * Add a named logger.  This does nothing and returns false if a logger
     * with the same name is already registered.
     * <p>
     * The Logger factory methods call this method to register each
     * newly created Logger.
     * <p>
     * The application should retain its own reference to the Logger 
     * object to avoid it being garbage collected.  The LogManager
     * may only retain a weak reference.
     *
     * @param   logger the new logger.
     * @return  true if the argument logger was registered successfully,
     *          false if a logger of that name already exists.
     * @exception NullPointerException if the logger name is null.
     */
    public synchronized boolean addLogger(Logger logger) {
	String name = logger.getName();
	if (name == null) {
	    throw new NullPointerException();
	}

	Logger old = (Logger) loggers.get(name);
	if (old != null) {
	    // We already have a registered logger with the given name.
	    return false;
	}

	// We're adding a new logger.
	// Note that we are creating a strong reference here that will
	// keep the Logger in existence indefinitely.
	loggers.put(name, logger);

	// Apply any initial level defined for the new logger.
	Level level = getLevelProperty(name+".level", null);
	if (level != null) {
	    doSetLevel(logger, level);
	}

	// If any of the logger's parents have levels defined,
	// make sure they are instantiated.
	int ix = 1;
	for (;;) {
	    int ix2 = name.indexOf(".", ix);
	    if (ix2 < 0) {
		break;
	    }
	    String pname = name.substring(0,ix2);
	    if (getProperty(pname+".level") != null) {
		// This pname has a level definition.  Make sure it exists.
		Logger plogger = Logger.getLogger(pname);
	    }
	    ix = ix2+1;
	}

	// Find the new node and its parent.
	LogNode node = findNode(name);
	node.logger = logger;
	Logger parent = null;
	LogNode nodep = node.parent;
	while (nodep != null) {
	    if (nodep.logger != null) {
		parent = nodep.logger;
		break;
	    }
	    nodep = nodep.parent;
	}

	if (parent != null) {
            doSetParent(logger, parent);
	}
	// Walk over the children and tell them we are their new parent.
	node.walkAndSetParent(logger);

	return true;
    }
Esempio n. 19
0
 void setConfig(Configuration config) {
   log.debug("config: " + config);
   proxyHost = config.get(PARAM_PROXY_HOST);
   proxyPort = config.getInt(PARAM_PROXY_PORT, DEFAULT_PROXY_PORT);
   if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
     String http_proxy = System.getenv("http_proxy");
     if (!StringUtil.isNullString(http_proxy)) {
       try {
         HostPortParser hpp = new HostPortParser(http_proxy);
         proxyHost = hpp.getHost();
         proxyPort = hpp.getPort();
       } catch (HostPortParser.InvalidSpec e) {
         log.warning("Can't parse http_proxy environment var, ignoring: " + http_proxy + ": " + e);
       }
     }
   }
   if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
     proxyHost = null;
   } else {
     log.info("Proxying through " + proxyHost + ":" + proxyPort);
   }
   userAgent = config.get(PARAM_USER_AGENT);
   if (StringUtil.isNullString(userAgent)) {
     userAgent = null;
   } else {
     log.debug("Setting User-Agent to " + userAgent);
   }
 }
Esempio n. 20
0
  /**
   * Put the JAIN-SIP stack in a state where it cannot receive any data and frees the network ports
   * used. That is to say remove JAIN-SIP <tt>ListeningPoint</tt>s and <tt>SipProvider</tt>s.
   */
  @SuppressWarnings("unchecked") // jain-sip legacy code
  private void stopListening() {
    try {
      this.secureJainSipProvider.removeSipListener(this);
      this.stack.deleteSipProvider(this.secureJainSipProvider);
      this.secureJainSipProvider = null;
      this.clearJainSipProvider.removeSipListener(this);
      this.stack.deleteSipProvider(this.clearJainSipProvider);
      this.clearJainSipProvider = null;

      Iterator<ListeningPoint> it = this.stack.getListeningPoints();
      Vector<ListeningPoint> lpointsToRemove = new Vector<ListeningPoint>();
      while (it.hasNext()) {
        lpointsToRemove.add(it.next());
      }

      it = lpointsToRemove.iterator();
      while (it.hasNext()) {
        this.stack.deleteListeningPoint(it.next());
      }

      this.stack.stop();
      if (logger.isTraceEnabled()) logger.trace("stopped listening");
    } catch (ObjectInUseException ex) {
      logger.fatal("Failed to stop listening", ex);
    }
  }
  /** Creates a Pooled connection and adds it to the connection pool. */
  private void installConnection() throws EmanagerDatabaseException {
    logger.debug("enter");

    PooledConnection connection;

    try {
      connection = poolDataSource.getPooledConnection();
      connection.addConnectionEventListener(this);
      connection.getConnection().setAutoCommit(false);
      synchronized (connectionPool) {
        connectionPool.add(connection);
        logger.debug("Database connection added.");
      }
    } catch (SQLException ex) {
      logger.fatal("exception caught while obtaining database " + "connection: ex = " + ex);
      SQLException ex1 = ex.getNextException();
      while (ex1 != null) {
        logger.fatal("chained sql exception ex1 = " + ex1);
        SQLException nextEx = ex1.getNextException();
        ex1 = nextEx;
      }
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.DatabaseConnectionFailure.getStatusCodeDescription()
              + ex.getMessage();

      logger.fatal(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.DatabaseConnectionFailure, logString);
      throw ede;
    }
  }
Esempio n. 22
0
 public void export() {
   log.debug("export(" + au.getName() + ")");
   log.debug(
       "dir: "
           + dir
           + ", pref: "
           + prefix
           + ", size: "
           + maxSize
           + ", ver: "
           + maxVersions
           + (compress ? ", (C)" : ""));
   checkArgs();
   try {
     start();
   } catch (IOException e) {
     recordError("Error opening file", e);
     return;
   }
   writeFiles();
   try {
     finish();
   } catch (IOException e) {
     if (!isDiskFull) {
       // If we already knew (and reported) disk full, also reporting it
       // as a close error is misleading.
       recordError("Error closing file", e);
     }
   }
 }
  /**
   * Tries to obtain a mapped/public address for the specified port (possibly by executing a STUN
   * query).
   *
   * @param dst the destination that we'd like to use this address with.
   * @param port the port whose mapping we are interested in.
   * @return a public address corresponding to the specified port or null if all attempts to
   *     retrieve such an address have failed.
   * @throws IOException if an error occurs while stun4j is using sockets.
   * @throws BindException if the port is already in use.
   */
  public InetSocketAddress getPublicAddressFor(InetAddress dst, int port)
      throws IOException, BindException {
    if (!useStun || (dst instanceof Inet6Address)) {
      logger.debug(
          "Stun is disabled for destination "
              + dst
              + ", skipping mapped address recovery (useStun="
              + useStun
              + ", IPv6@="
              + (dst instanceof Inet6Address)
              + ").");
      // we'll still try to bind though so that we could notify the caller
      // if the port has been taken already.
      DatagramSocket bindTestSocket = new DatagramSocket(port);
      bindTestSocket.close();

      // if we're here then the port was free.
      return new InetSocketAddress(getLocalHost(dst), port);
    }
    StunAddress mappedAddress = queryStunServer(port);
    InetSocketAddress result = null;
    if (mappedAddress != null) result = mappedAddress.getSocketAddress();
    else {
      // Apparently STUN failed. Let's try to temporarily disble it
      // and use algorithms in getLocalHost(). ... We should probably
      // eveng think about completely disabling stun, and not only
      // temporarily.
      // Bug report - John J. Barton - IBM
      InetAddress localHost = getLocalHost(dst);
      result = new InetSocketAddress(localHost, port);
    }
    if (logger.isDebugEnabled())
      logger.debug("Returning mapping for port:" + port + " as follows: " + result);
    return result;
  }
  /** Create LockssKeystores from config subtree below {@link #PARAM_KEYSTORE} */
  void configureKeyStores(Configuration config) {
    Configuration allKs = config.getConfigTree(PARAM_KEYSTORE);
    for (Iterator iter = allKs.nodeIterator(); iter.hasNext(); ) {
      String id = (String) iter.next();
      Configuration oneKs = allKs.getConfigTree(id);
      try {
        LockssKeyStore lk = createLockssKeyStore(oneKs);
        String name = lk.getName();
        if (name == null) {
          log.error("KeyStore definition missing name: " + oneKs);
          continue;
        }
        LockssKeyStore old = keystoreMap.get(name);
        if (old != null && !lk.equals(old)) {
          log.warning(
              "Keystore "
                  + name
                  + " redefined.  "
                  + "New definition may not take effect until daemon restart");
        }

        log.debug("Adding keystore " + name);
        keystoreMap.put(name, lk);

      } catch (Exception e) {
        log.error("Couldn't create keystore: " + oneKs, e);
      }
    }
  }
Esempio n. 25
0
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
Esempio n. 26
0
 protected List<MappingWithDirection> findApplicable(MappingKey key) {
   ArrayList<MappingWithDirection> result = new ArrayList<MappingWithDirection>();
   for (ParsedMapping pm : mappings) {
     if ((pm.mappingCase == null && key.mappingCase == null)
         ^ (pm.mappingCase != null && pm.mappingCase.equals(key.mappingCase))) {
       if (pm.sideA.isAssignableFrom(key.source) && pm.sideB.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, true));
       else if (pm.sideB.isAssignableFrom(key.source) && pm.sideA.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, false));
     }
   }
   if (!result.isEmpty()) {
     Collections.sort(result, new MappingComparator(key.target));
   } else if (automappingEnabled) {
     logger.info(
         "Could not find applicable mappings between {} and {}. A mapping will be created using automapping facility",
         key.source.getName(),
         key.target.getName());
     ParsedMapping pm = new Mapping(key.source, key.target, this).automap().parse();
     logger.debug("Automatically created {}", pm);
     mappings.add(pm);
     result.add(new MappingWithDirection(pm, true));
   } else
     logger.warn(
         "Could not find applicable mappings between {} and {}!",
         key.source.getName(),
         key.target.getName());
   return result;
 }
Esempio n. 27
0
  /** @param aProperties the updated properties. */
  @SuppressWarnings("rawtypes")
  final void setProperties(final Dictionary aProperties) {
    final Map<String, String> newProps = new HashMap<String, String>();

    Enumeration keys = aProperties.keys();
    while (keys.hasMoreElements()) {
      final String key = (String) keys.nextElement();
      if (!KNOWN_KEYS.contains(key) && !IGNORED_KEYS.contains(key)) {
        LOG.log(Level.WARNING, "Unknown/unsupported profile key: " + key);
        continue;
      }

      final String value = aProperties.get(key).toString();
      newProps.put(key, value.trim());
    }

    // Verify whether all known keys are defined...
    final List<String> checkedKeys = new ArrayList<String>(KNOWN_KEYS);
    checkedKeys.removeAll(newProps.keySet());
    if (!checkedKeys.isEmpty()) {
      throw new IllegalArgumentException(
          "Profile settings not complete! Missing keys are: " + checkedKeys.toString());
    }

    this.properties.putAll(newProps);

    LOG.log(
        Level.INFO,
        "New device profile settings applied for {1} ({0}) ...", //
        new Object[] {getType(), getDescription()});
  }
Esempio n. 28
0
  /**
   * 返回响应结果
   *
   * @param response
   * @return
   */
  public static RestResponse returnResponse(
      BaseRestRequest request,
      RestResponse response,
      RestServiceMapping serviceMapping,
      RestServiceConfiguration configuration) {

    String cmd = request.getRestRequest().getCmd();

    // 调用后置拦截器
    List<RestRequestAfterInterceptor> requestAfterInterceptors =
        configuration.getRequestAfterInterceptors();
    for (RestRequestAfterInterceptor requestInterceptor : requestAfterInterceptors) {
      String requestInterceptorName = requestInterceptor.getName();
      logger.debug(
          "REST_AFTER_INTERCEPTOR_START, cmd: {}, name: {}",
          cmd,
          requestInterceptorName + "|" + requestInterceptor.getClass().getName());
      try {
        requestInterceptor.setConfiguration(configuration);
        requestInterceptor.execute(serviceMapping, request, response);
      } catch (Exception e) {
        response.setException(e);
        logger.warn("执行拦截器 {} 失败", requestInterceptorName, e);
      }
      logger.debug(
          "REST_AFTER_INTERCEPTOR_COMPLETE, cmd: {}, name: {}",
          cmd,
          requestInterceptorName + "|" + requestInterceptor.getClass().getName());
    }
    return response;
  }
Esempio n. 29
0
 private void initTestPolls() throws Exception {
   testV1polls = new V1Poll[testV1msg.length];
   for (int i = 0; i < testV1polls.length; i++) {
     log.debug3("initTestPolls: V1 " + i);
     BasePoll p = pollmanager.makePoll(testV1msg[i]);
     assertNotNull(p);
     assertNotNull(p.getMessage());
     log.debug("initTestPolls: V1 " + i + " returns " + p);
     assertTrue(p instanceof V1Poll);
     switch (i) {
       case 0:
         assertTrue(p instanceof V1NamePoll);
         break;
       case 1:
         assertTrue(p instanceof V1ContentPoll);
         break;
       case 2:
         assertTrue(p instanceof V1VerifyPoll);
         break;
     }
     testV1polls[i] = (V1Poll) p;
     assertNotNull(testV1polls[i]);
     log.debug3("initTestPolls: " + i + " " + p.toString());
   }
 }
Esempio n. 30
0
  public void render(FacesContext context) throws FacesException {
    if (context.getResponseComplete()) return;

    Application app = context.getApplication();
    ViewHandler view = app.getViewHandler();

    beforePhase(context, PhaseId.RENDER_RESPONSE);

    try {
      if (log.isLoggable(Level.FINER)) log.finer(context.getViewRoot() + " before render view");

      view.renderView(context, context.getViewRoot());
    } catch (java.io.IOException e) {
      if (sendError(context, "renderView", e)) return;

      throw new FacesException(e);
    } catch (RuntimeException e) {
      if (sendError(context, "renderView", e)) return;

      throw e;
    } finally {
      afterPhase(context, PhaseId.RENDER_RESPONSE);

      logMessages(context);
    }
  }