Ejemplo n.º 1
0
  public static Context initContext(String context_url) {

    Context initContext = null;
    try {
      initContext = new InitialContext();
    } catch (NamingException e) {
      System.out.println("ERROR: initContext(): Could not get InitalContext");
      e.printStackTrace();
      Logger logger = Logger.getLogger(DatabaseData.class);
      logger.error("DatabaseData.initContext(): ", e);
    }

    Context ctx = null;
    try {
      ctx = (Context) initContext.lookup(context_url);
    } catch (NamingException e) {
      System.out.println("ERROR: initContext(): Could not init Context");
      e.printStackTrace();
      System.out.println(
          "DatabaseData().initContext() Exiting!!!!! Setup the context: " + context_url);
      Logger logger = Logger.getLogger(DatabaseData.class);
      logger.error("DatabaseData.initContext(): Exiting", e);
      System.exit(1);
    }

    return ctx;
  }
Ejemplo n.º 2
0
  /**
   * calculate summ for given order
   *
   * @param orderId
   * @return
   */
  @Override
  public double calculateSumm(int orderId) {
    Connection connection = MyConnection.getInstance().getConnection();
    double summ = 0;
    LinkedList<Integer> orderList = selectAllByOrderId(orderId);
    try {
      for (int i = 0; i < orderList.size(); i++) {
        PreparedStatement preparedStatement =
            connection.prepareStatement("select * from dish where dishId = ?");
        preparedStatement.setInt(1, orderList.get(i));
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
          summ += resultSet.getDouble(MYSQL_PRICE.toString());
        }
      }

    } catch (SQLException | NullPointerException ex) {
      Logger.getLogger(MySQLOrderDAO.class.getName()).error(ex);
    } finally {
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(MySQLOrderDAO.class.getName()).error(ex);
      }
    }
    return summ;
  }
Ejemplo n.º 3
0
  /**
   * get a summ for order
   *
   * @param orderId
   * @return
   */
  @Override
  public double getOrderSumm(int orderId) {
    Connection connection = MyConnection.getInstance().getConnection();
    double summ = 0;
    try {
      PreparedStatement preparedStatement =
          connection.prepareStatement("select * from order_table where orderId = ?");
      preparedStatement.setInt(1, orderId);
      ResultSet resultSet = preparedStatement.executeQuery();

      if (resultSet.next()) {
        summ = resultSet.getDouble(MYSQL_SUMM.toString());
      }

    } catch (SQLException | NullPointerException ex) {
      Logger.getLogger(MySQLOrderDAO.class.getName()).error(ex);
    } finally {
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(MySQLOrderDAO.class.getName()).error(ex);
      }
    }
    return summ;
  }
Ejemplo n.º 4
0
  /**
   * select ids of all content of an order
   *
   * @param orderId order id
   * @return a list of dish ids in given order
   */
  @Override
  public LinkedList<Integer> selectAllByOrderId(int orderId) {
    LinkedList<Integer> dishIdList = new LinkedList();

    Connection connection = MyConnection.getInstance().getConnection();
    try {
      PreparedStatement preparedStatement =
          connection.prepareStatement("select * from order_content where orderID = ?");
      preparedStatement.setInt(1, orderId);
      ResultSet resultSet = preparedStatement.executeQuery();

      while (resultSet.next()) {
        dishIdList.add(resultSet.getInt(MYSQL_DISH_ID.toString()));
      }

    } catch (SQLException | NullPointerException ex) {
      Logger.getLogger(MySQLOrderDAO.class.getName()).error(ex);
    } finally {
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(MySQLOrderDAO.class.getName()).error(ex);
      }
    }

    return dishIdList;
  }
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   HttpSession session = request.getSession();
   Object typeAttr = session.getAttribute(User.TYPE);
   if (typeAttr == null) {
     Logger.getLogger(AuthorityInterceptor.class)
         .warn("errorCode:" + ErrorCode.ILLEGAL_ACCESS_ERROR + " from:" + getIpAddress(request));
     response.setContentType("application/json;charset=UTF-8");
     Writer writer = response.getWriter();
     writer.append(jsonUtil.setFailRes(ErrorCode.ILLEGAL_ACCESS_ERROR).toJson());
     writer.flush();
     writer.close();
     return false;
   }
   int userType = (int) typeAttr;
   if (userType != type) {
     // 指定类型的url,只能有指定类型的用访问
     Logger.getLogger(AuthorityInterceptor.class)
         .warn(
             "errorCode:" + ErrorCode.PERMISSION_DENIED_ERROR + " from:" + getIpAddress(request));
     response.setContentType("application/json;charset=UTF-8");
     Writer writer = response.getWriter();
     writer.append(jsonUtil.setFailRes(ErrorCode.PERMISSION_DENIED_ERROR).toJson());
     writer.flush();
     writer.close();
     return false;
   }
   return true;
 }
Ejemplo n.º 6
0
  public static <V, E> Neo4jTopology loadTopology(Neo4jWorkspaceSettings settings)
      throws Exception {
    String db = DatabaseConfiguration.readDatabase(settings);
    Logger.getLogger(Neo4jWorkspace.class).info("using db " + db);

    // Get neo4j stuffs
    GraphDatabaseFactory factory = new GraphDatabaseFactory();
    GraphDatabaseService database = factory.newEmbeddedDatabase(db);
    GlobalGraphOperations operation = GlobalGraphOperations.at(database);

    ViewsManager views = new ViewsManager();
    views.load(settings);

    // Setup graph model
    Neo4jGraphModelIO gio = new Neo4jGraphModelIO();
    gio.read(SimpleFile.read(settings.getModelPath()));
    Neo4jGraphModel typeModel = gio.getGraphModel();

    // Build graph
    INeo4jGraphReader r = views.getFirst().getFilter();
    Graph<IPropertyNode, IPropertyEdge> graph = r.read(operation, typeModel);
    Logger.getLogger(Neo4jWorkspace.class)
        .info("filtered graph has " + graph.getVertexCount() + " nodes using db " + db);

    // Build topology using graph typing model
    String topologyName = views.getFirst().getTopologyName();
    Neo4jTopologyFactory tfact = new Neo4jTopologyFactory();
    Neo4jTopology topology = tfact.newTopology(topologyName, graph, typeModel);

    return topology;
  }
 @Override
 public boolean importData(TransferSupport support) {
   DataFlavor f = getStringFlavor(support.getDataFlavors());
   Object drop = null;
   String s = null;
   if (f != null) {
     try {
       drop = support.getTransferable().getTransferData(f);
     } catch (UnsupportedFlavorException e) {
       Logger.getLogger(this.getClass()).debug("Internal error.", e); // $NON-NLS-1$
     } catch (IOException e) {
       Logger.getLogger(this.getClass()).debug("Internal error.", e); // $NON-NLS-1$
     }
   } else {
     try {
       drop = support.getTransferable().getTransferData(DataFlavor.stringFlavor);
     } catch (UnsupportedFlavorException e) {
       Logger.getLogger(this.getClass()).debug("Internal error.", e); // $NON-NLS-1$
     } catch (IOException e) {
       Logger.getLogger(this.getClass()).debug("Internal error.", e); // $NON-NLS-1$
     }
   }
   if (drop != null) {
     s = String.valueOf(drop);
   }
   if (s != null) {
     return importString(s, support);
   }
   return false;
 }
Ejemplo n.º 8
0
  /**
   * Invoke, and turn objects back into Java-accessible objects.
   *
   * @param command the command
   * @return the object[]
   */
  public Object[] invoke(String command) {
    Object[] rv = null;
    try {
      switch (scriptType) {
        case JAVASCRIPT:
          NativeArray arr = (NativeArray) jsInvocable.invokeFunction(command);
          rv = new Object[(int) arr.getLength()];

          // get as object
          for (Object o : arr.getIds()) {
            int index = (Integer) o;
            rv[index] = arr.get(index, null);
          }
          break;
        case RUBY:
          rv = (Object[]) rbInvocable.invokeFunction(command);
      }
    } catch (NoSuchMethodException e) {
      org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scripts");
      fLog.error("Script invocation failed.", e);
    } catch (ScriptException e) {
      org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scripts");
      fLog.error("Script invocation failed.", e);
    }
    return rv;
  }
Ejemplo n.º 9
0
    @Override
    public void onMessage(String s) {
      Logger.getLogger("").info("Mensaje: " + s);
      try {
        JSONObject json = new JSONObject(s);
        String command = json.getString("command");
        Logger.getLogger("").info("Comando recibido: '" + command + "'");

        if (command.equals("getVentas")) {
          publishVentaDia();
        }
        if (command.equals("getProductos")) {
          new Thread() {
            public void run() {
              publishProductos();
            }
          }.start();
        }
        if (command.equals("pong")) {
          ping = false;
        }
      } catch (JSONException e) {
        Logger.getLogger(WebSocketWS.class).error("Error convirtiendo JSON entrante");
      }
    }
 protected EditorModelHandler getHandler(String propertyName) {
   EditorModelHandler handler = propertyHandlerMap.get(propertyName);
   if (handler == null) {
     try {
       for (WidgetModel widget : widgets) {
         if (widget.getWidgetEditor() instanceof DefaultTableWidgetPropertiesEditor) {
           handler =
               ((DefaultTableWidgetPropertiesEditor) widget.getWidgetEditor())
                   .propertyHandlerMap.get(propertyName);
           if (handler != null) break;
         }
       }
     } catch (Exception e) {
       // the below comment isn't clear. I wish I knew when to expect this.
       Logger.getLogger(DefaultTableWidgetPropertiesEditor.class)
           .error("couldn't get a handler for: " + propertyName, e);
       // no registered editor, or unknown property
     }
     if (handler == null) {
       Logger.getLogger(DefaultTableWidgetPropertiesEditor.class)
           .error("", new Exception("No handler for: " + propertyName));
     }
   }
   return handler;
 }
Ejemplo n.º 11
0
public class LogRecord {

  /** 一般情况记录到/logs/log_info.txt 错误信息记录到/logs/log_error.txt */
  public static Logger warn = Logger.getLogger("InfoLogger");

  public static Logger error = Logger.getLogger("ErrorLogger");
}
Ejemplo n.º 12
0
 /**
  * Put new accident and reorder accident
  *
  * @param accident
  */
 public void put(Accident accident) {
   getStack().add(accident);
   Collections.sort(getStack());
   Logger.getLogger(ActivationStack.class).debug("********************{");
   Logger.getLogger(ActivationStack.class).debug(this.toString());
   Logger.getLogger(ActivationStack.class).debug("}********************");
 }
  /** @param args */
  public static void main(String[] args) throws Exception {
    BasicConfigurator.configure();
    Logger.getLogger("org.eclipse.emf.teneo").setLevel(Level.INFO);
    Logger.getLogger("org.hibernate").setLevel(Level.WARN);

    DatabaseSetupData setupData = new DatabaseSetupData();

    if (args != null && args.length > 0) {
      setupData.setSchemaFileName(args[0]);
      if (args.length > 1) {
        setupData.setDatabaseName(args[1]);
      }
    }

    if (!DatabaseSetupUtil.testServerConnection(setupData)) {
      throw new RuntimeException("Unable to connect to running server");
    }

    if (DatabaseSetupUtil.checkDatabaseExists(setupData)) {
      throw new RuntimeException("Database: '" + setupData.getDatabaseName() + "' exists!");
    }

    // documentation
    DatabaseSetupUtil.generateSchemaFile(setupData);
    DatabaseSetupUtil.generateHibernateMapping(setupData);

    // create live database
    DatabaseSetupUtil.createDatabase(setupData);

    // create seed data and initial dairy record
    DatabaseSetupUtil setupUtil = new DatabaseSetupUtil(setupData);
    setupUtil.intializeDairyDatabase("registration #", "licensee name");
  }
Ejemplo n.º 14
0
  /**
   * Notifies all the <code>GroupListener<code> objects, about members added/removed.
   *
   * @param event Group event
   * @param added <code>true</code> if members were added, <code>false</code> otherwise.
   */
  protected void fireGroupEvent(DeviceGroupEvent<T> event, boolean added) {
    if (groupListeners == null) {
      return;
    }

    DeviceGroupListener<T>[] l = (DeviceGroupListener<T>[]) groupListeners.toArray();

    if (added) {
      for (int i = 0; i < l.length; i++) {
        try {
          l[i].membersAdded(event);
        } catch (Exception e) {
          Logger.getLogger(DeviceCollectionMap.class)
              .warn("Error in event handler, continuing.", e);
        }
      }
    } else {
      for (int i = 0; i < l.length; i++) {
        try {
          l[i].membersRemoved(event);
        } catch (Exception e) {
          Logger.getLogger(DeviceCollectionMap.class)
              .warn("Error in event handler, continuing.", e);
        }
      }
    }
  }
  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());
    }
  }
Ejemplo n.º 16
0
  public static void main(String[] args) throws Exception {

    Randomizer.init(14L); // initialize common random seed.

    // turn off debug logs
    Logger orstlog = Logger.getLogger("orst");
    Logger msglog = Logger.getLogger("msglog");
    orstlog.setLevel(Level.OFF);
    msglog.setLevel(Level.OFF);

    // where to write results?
    if (args.length >= 1) {
      dir = args[0];
    }
    System.out.println("Writing result YAML files to '" + dir + "'.");

    String[] gameFiles = {
      "2bases-game.txt", // in stratsim module.
      "the-right-strategy-game.txt", // in stratplan module.
    };
    String[] strategy_sets = {"2012-02-05" /* "atk-dfnd", "synth" */};

    for (String name : strategy_sets) {
      sim_matrix(gameFiles, name);
      System.out.println(name + " strategy set done.");
    }
    System.out.println("Done!");
  }
  @Override
  public void getExtraResponse() {
    try {
      Logger.getLogger(this.getClass()).info("[EXTRA-QUORUM] Getting last server info");
      String lastServerURL = getReplicasNotResponded(responseList.keySet(), urlList);

      Logger.getLogger(this.getClass()).info("[EXTRA-QUORUM] Last Server : " + lastServerURL);
      AnacomPortType port = getPortType(lastServerURL);

      // Sync Replica request
      responseType = port.getBalanceAndPhoneList(operatorSimpleTypeRequest);

      // Save vote
      BalanceAndPhoneListType type = (BalanceAndPhoneListType) responseType;
      voteList.addVote(type.getVersion(), responseType);

      // Vote again
      responseType = voteList.getBestResponse(getReplicaLength());

      // If cant find best answer with all replicas then is catastrophe
      if (responseType == null) {
        Logger.getLogger(this.getClass()).info("[ERR] JA FOSTE");
        System.exit(-1);
      }
    } catch (OperatorPrefixDoesNotExistRemoteException e) {
      throw new OperatorPrefixDoesNotExistException(e.getFaultInfo().getOperatorPrefix());
    }
  }
Ejemplo n.º 18
0
  /** Initialize. */
  private void initialize() {
    try {
      switch (scriptType) {
        case JAVASCRIPT:
          jsEngine.eval(jsBase + script);
          break;
          // TODO fix ruby scripts breaking on windows
        case RUBY:
          rbEngine.eval(rbBase + script);
          break;
      }
    } catch (ScriptException e) {

      new NSAlertBox(
          "Script Read Error",
          reference.getName()
              + " has an error. Due to error reporting methods, I can not help you narrow down the issue. Here is a stack trace:\n"
              + e.getMessage(),
          SWT.ICON_ERROR);

      org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scripts");
      fLog.error(
          "Script initialization failed: "
              + reference.getName()
              + " at line #"
              + e.getLineNumber());
    } catch (Exception e) {
      org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scripts");
      fLog.error("Script initialization failed: " + e.getStackTrace());
    }
  }
Ejemplo n.º 19
0
 protected void startATKWizard() throws PhoneException {
   Logger.getLogger(this.getClass()).debug("Starting ATK Wizard");
   // run ATKWizard
   try {
     device.executeShellCommand(
         "am start -n com.orange.atk.wizard/.ATKWizardClient", shellOutputReceiver);
   } catch (IOException e) {
     e.printStackTrace();
     throw new PhoneException("ATK Wizard - unable to launch ATK Wizard");
   } catch (TimeoutException e) {
     e.printStackTrace();
     throw new PhoneException("ATK Wizard - unable to launch ATK Wizard");
   } catch (AdbCommandRejectedException e) {
     e.printStackTrace();
     throw new PhoneException("ATK Wizard - unable to launch ATK Wizard");
   } catch (ShellCommandUnresponsiveException e) {
     e.printStackTrace();
     throw new PhoneException("ATK Wizard - unable to launch ATK Wizard");
   }
   try {
     Thread.sleep(1000);
   } catch (InterruptedException e2) {
   }
   Logger.getLogger(this.getClass()).debug("ATK Wizard is launched on the device ...");
 }
  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
        }
      }
    }
  }
  @Override
  public void sendToReplicas() {
    for (String url : urlList) {

      AnacomPortType port = null;

      Logger.getLogger(this.getClass())
          .info(
              "[ANACOM] Async getBalanceAndPhoneList : "
                  + operatorDto.getOperatorPrefix()
                  + " | New version : "
                  + nextVersion);

      try {
        port = getPortType(url);
      } catch (Exception e) {
        Logger.getLogger(this.getClass())
            .info("[ERR] Nao foi possivel contactar a replica: " + url);
      }

      // Async Replica request
      if (port != null) {
        QuorumBalanceAndPhoneListResponse handlerResponse =
            new QuorumBalanceAndPhoneListResponse(url, this);
        addHandler(handlerResponse);
        setSecurityHandlers(port);
        Logger.getLogger(this.getClass()).info("NOVO HANDLER GET: " + handlerResponse);
        port.getBalanceAndPhoneListAsync(operatorSimpleTypeRequest, handlerResponse);
      }
    }
  }
  @Override
  public void setupLogging() throws Exception {
    Logger.getLogger("de.uniluebeck.itm.ncoap.communication.ClientGetsNoAckForConRequestTest")
        .setLevel(Level.INFO);

    Logger.getLogger("de.uniluebeck.itm.ncoap.endpoints").setLevel(Level.INFO);
  }
Ejemplo n.º 23
0
  /**
   * @param pConfig The physical source config for which the event producer is configured.
   * @param schemaRegistryService Schema registry to fetch schemas
   * @param dbusEventBuffer An event buffer to which the producer can write/append events.
   * @param statsCollector Reporting stats
   * @param maxScnReaderWriters To read/write the maxScn from maxScn file
   * @throws DatabusException
   */
  public GoldenGateEventProducer(
      PhysicalSourceStaticConfig pConfig,
      SchemaRegistryService schemaRegistryService,
      DbusEventBufferAppendable dbusEventBuffer,
      DbusEventsStatisticsCollector statsCollector,
      MaxSCNReaderWriter maxScnReaderWriters)
      throws DatabusException {
    super(dbusEventBuffer, maxScnReaderWriters, pConfig, null);
    _pConfig = pConfig;
    _schemaRegistryService = schemaRegistryService;
    _statsCollector = statsCollector;
    _currentState = State.INIT;
    _partitionFunctionHashMap = new HashMap<Integer, PartitionFunction>();
    _eventsLog = Logger.getLogger("com.linkedin.databus2.producers.db.events." + pConfig.getName());

    if (_pConfig != null) {
      long eventRatePerSec = pConfig.getEventRatePerSec();
      long maxThrottleDurationInSecs = pConfig.getMaxThrottleDurationInSecs();

      if ((eventRatePerSec > 0) && (maxThrottleDurationInSecs > 0)) {
        _rc = new RateControl(eventRatePerSec, maxThrottleDurationInSecs);
      } else {
        // Disable rate control
        _rc = new RateControl(Long.MIN_VALUE, Long.MIN_VALUE);
      }
    }

    final String MODULE = GoldenGateEventProducer.class.getName();
    _log = Logger.getLogger(MODULE + "." + getName());

    // Create a hashmap for logical source id ==> PartitionFunction, this will be used as the
    // logical partition Id for the event creation
    // also create a list(map) of MonitoredSourceInfo objects to monitor GGEventProducer progress
    for (int i = 0; i < _pConfig.getSources().length; i++) {
      LogicalSourceStaticConfig logicalSourceStaticConfig = _pConfig.getSources()[i];
      GGMonitoredSourceInfo source =
          buildGGMonitoredSourceInfo(logicalSourceStaticConfig, _pConfig);
      _monitoredSources.put(source.getSourceId(), source);
    }

    // get one fake global source for total stats
    LogicalSourceStaticConfig logicalSourceStaticConfig =
        new LogicalSourceStaticConfig(
            GLOBAL_SOURCE_ID,
            _pConfig.getName(),
            "",
            "constant:1",
            (short) 0,
            false,
            null,
            null,
            null);
    GGMonitoredSourceInfo source = buildGGMonitoredSourceInfo(logicalSourceStaticConfig, _pConfig);
    _monitoredSources.put(source.getSourceId(), source);

    // create stats collector for parser
    _ggParserStats = new GGParserStatistics(_pConfig.getName());
    registerParserMbean(_ggParserStats);
  }
Ejemplo n.º 24
0
/**
 * @description
 * @author <a href="*****@*****.**">junyu</a>
 * @version 1.0
 * @since 1.6
 * @date 2011-8-25下午02:48:05
 */
public class TotalLogInit {
  public static final Logger DB_TAB_LOG = Logger.getLogger("DB_TAB_LOG");
  public static final Logger VSLOT_LOG = Logger.getLogger("VSLOT_LOG");
  public static final Logger DYNAMIC_RULE_LOG = Logger.getLogger("DYNAMIC_RULE_LOG");

  private static volatile boolean initOK = false;

  private static String getLogPath() {
    String userHome = System.getProperty("user.home");
    if (!userHome.endsWith(File.separator)) {
      userHome += File.separator;
    }
    String path = userHome + "logs" + File.separator + "tddl" + File.separator;
    File dir = new File(path);
    if (!dir.exists()) {
      dir.mkdirs();
    }
    return path;
  }

  static {
    initTddlLog();
  }

  private static Appender buildAppender(String name, String fileName, String pattern) {
    DailyRollingFileAppender appender = new DailyRollingFileAppender();
    appender.setName(name);
    appender.setAppend(true);
    appender.setEncoding("GBK");
    appender.setLayout(new PatternLayout(pattern));
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());
    appender.activateOptions(); // 很重要,否则原有日志内容会被清空
    return appender;
  }

  public static void initTddlLog() {
    if (initOK) return;
    Appender dbTabAppender = buildAppender("TDDL_Vtab_Appender", "tddl-db-tab.log", "%m");
    Appender vSlotAppender = buildAppender("TDDL_Vtab_Appender", "tddl-vslot.log", "%m");
    Appender dynamicRuleAppender =
        buildAppender("TDDL_DynamicRule_Appender", "tddl-dynamic-rule.log", "%m");

    DB_TAB_LOG.setAdditivity(false);
    DB_TAB_LOG.removeAllAppenders();
    DB_TAB_LOG.addAppender(dbTabAppender);
    DB_TAB_LOG.setLevel(Level.INFO);

    VSLOT_LOG.setAdditivity(false);
    VSLOT_LOG.removeAllAppenders();
    VSLOT_LOG.addAppender(vSlotAppender);
    VSLOT_LOG.setLevel(Level.INFO);

    DYNAMIC_RULE_LOG.setAdditivity(false);
    DYNAMIC_RULE_LOG.removeAllAppenders();
    DYNAMIC_RULE_LOG.addAppender(dynamicRuleAppender);
    DYNAMIC_RULE_LOG.setLevel(Level.INFO);
  }
}
Ejemplo n.º 25
0
  /**
   * Build full Neo4jWorkspace involving reading files given by settings:
   *
   * <ul>
   *   <li>neo4j database
   *   <li>view
   *   <li>graph model
   *   <li>projection
   * </ul>
   *
   * and build topology & geometrical model according to Neo4j factories
   *
   * @param settings
   * @throws Exception
   */
  public Neo4jWorkspace(Neo4jWorkspaceSettings settings) throws Exception {
    String db = DatabaseConfiguration.readDatabase(settings);
    Logger.getLogger(Neo4jWorkspace.class).info("using db " + db);

    // Get neo4j stuffs
    GraphDatabaseFactory factory = new GraphDatabaseFactory();
    database = factory.newEmbeddedDatabase(db);
    operation = GlobalGraphOperations.at(database);

    views = new ViewsManager();
    views.load(settings);
    layoutML = views.getFirst().getLayout();

    // Setup graph model
    Neo4jGraphModelIO gio = new Neo4jGraphModelIO();
    gio.read(SimpleFile.read(settings.getModelPath()));
    Neo4jGraphModel typeModel = gio.getGraphModel();

    // Build graph
    INeo4jGraphReader r = views.getFirst().getFilter();
    Graph<IPropertyNode, IPropertyEdge> graph = r.read(operation, typeModel);
    Logger.getLogger(Neo4jWorkspace.class)
        .info("filtered graph has " + graph.getVertexCount() + " nodes using db " + db);

    // Build topology using graph typing model
    String topologyName = views.getFirst().getTopologyName();
    Neo4jTopologyFactory tfact = new Neo4jTopologyFactory();
    topology = tfact.newTopology(topologyName, graph, typeModel);

    // Edit topology according to dataprism
    Dataprism dp = loadDataprism(settings);
    if (dp != null) ((Neo4jTopology) topology).edit().apply(dp);

    // Build layout model
    modelFactory = new Neo4jModelFactory(gio.getGraphModel());
    model = (IHierarchicalNodeModel) modelFactory.getLayoutModel(topology);
    edgeModel = model.getEdgeModel();
    applyLayoutMLConfiguration(model, layoutML);

    // Build layout
    layoutFactory = new Neo4jLayoutFactory(typeModel);
    if (layoutML != null) {
      Map<String, String> mapping = extractModelLayoutMapping(layoutML);
      layoutFactory.setModelLayoutMapping(mapping);
    }

    layout = layoutFactory.getLayout(model);
    layout.getEdgeLayout().setEdgePostProcess(null);

    // finalize workspace
    annotationModel = new AnnotationModel();
    metadata = null;
    setName(settings.getName());
    loadMapIfExist();

    this.configuration = new ConfigurationFacade(this);
  }
Ejemplo n.º 26
0
  public void removeExpired() {
    NodeList invitationList = invitationRoot.getElementsByTagName("invitation");

    if (invitationList == null) {
      return;
    }

    Vector expiredList = new Vector();

    int listLength = invitationList.getLength();

    for (int i = 0; i < listLength; i++) {
      Element invitationElement = (Element) invitationList.item(i);

      String expirationString = XmlUtil.getChildText(invitationElement, "expires");

      if (expirationString != null) {
        long expiration = 0L;

        try {
          expiration = Long.parseLong(expirationString);
        } catch (NumberFormatException nfe) {
        }

        if (System.currentTimeMillis() > expiration) {
          expiredList.add(invitationElement);
        }
      }
    }

    int expiredNum = expiredList.size();

    for (int i = expiredList.size() - 1; i >= 0; i--) {
      Element expiredElement = (Element) expiredList.elementAt(i);

      String type = XmlUtil.getChildText(expiredElement, "type");

      if ((type != null) && type.equals(INVITATION_TYPE_TREE)) {
        String virtualUser = XmlUtil.getChildText(expiredElement, "virtualUser");

        if ((virtualUser != null) && (virtualUser.trim().length() > 0)) {
          WebFileSys.getInstance().getUserMgr().removeUser(virtualUser);
          Logger.getLogger(getClass()).debug("expired virtual user " + virtualUser + " removed");
        }
      }

      invitationRoot.removeChild(expiredElement);
    }

    if (expiredNum > 0) {
      changed = true;
    }

    Logger.getLogger(getClass()).info(expiredNum + " expired invitations removed");
    Logger.getLogger(getClass()).info(expiredNum + " expired invitations removed");
  }
Ejemplo n.º 27
0
  private String runUnixCmd(String unixCmd) {
    StringBuffer buff = new StringBuffer();

    String cmdToExecute = unixCmd;

    if (WebFileSys.getInstance().getOpSysType() == WebFileSys.OS_AIX) {
      cmdToExecute = unixCmd + " 2>&1";
    }

    Logger.getLogger(getClass()).debug("executing command : " + cmdToExecute);

    String cmdWithParms[];

    if (WebFileSys.getInstance().getOpSysType() == WebFileSys.OS_AIX) {
      cmdWithParms = new String[2];
      cmdWithParms[0] = "/bin/sh";
      cmdWithParms[1] = cmdToExecute;
    } else {
      cmdWithParms = new String[3];
      cmdWithParms[0] = "/bin/sh";
      cmdWithParms[1] = "-c";
      cmdWithParms[2] = cmdToExecute + " 2>&1";
    }

    Runtime rt = Runtime.getRuntime();

    Process cmdProcess = null;

    try {
      cmdProcess = rt.exec(cmdWithParms);
    } catch (Exception e) {
      Logger.getLogger(getClass()).error("failed to run OS command", e);
    }

    DataInputStream cmdOut = new DataInputStream(cmdProcess.getInputStream());
    String stdoutLine = null;

    boolean done = false;

    try {
      while (!done) {
        stdoutLine = cmdOut.readLine();

        if (stdoutLine == null) {
          done = true;
        } else {
          buff.append(stdoutLine);
          buff.append('\n');
        }
      }
    } catch (IOException ioe) {
      Logger.getLogger(getClass()).error("failed to read OS command output", ioe);
    }

    return buff.toString();
  }
Ejemplo n.º 28
0
 public static void setLevel(String[] allLoggers, Level level) {
   Appender app = Logger.getLogger("jrds").getAppender(JrdsLoggerConfiguration.APPENDERNAME);
   for (String loggerName : allLoggers) {
     Logger l = Logger.getLogger(loggerName);
     l.setLevel(level);
     if (l.getAppender(JrdsLoggerConfiguration.APPENDERNAME) != null) {
       l.addAppender(app);
     }
   }
 }
/** @author Administrator */
public class ConverterReport {

  public static final Logger statictics = Logger.getLogger("Statistics");

  public static final Logger badFiles = Logger.getLogger("BadFiles");

  public static final Logger notSupportedExtention = Logger.getLogger("NotSupportedFiles");

  public static final Logger convertedFiles = Logger.getLogger("ConvertedFiles");
}
 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
   BasicConfigurator.configure();
   Logger.getLogger(CompositeMetadataProviderImpl.class).setLevel(Level.DEBUG);
   Logger.getLogger(AnnotationMetadataProviderImpl.class).setLevel(Level.DEBUG);
   Logger.getLogger(EclipseLinkJpaMetadataProviderImpl.class).setLevel(Level.DEBUG);
   jpaMetadataProvider = new EclipseLinkJpaMetadataProviderImpl();
   EntityManagerFactory entityManagerFactory =
       Persistence.createEntityManagerFactory("krad-data-unit-test");
   jpaMetadataProvider.setEntityManager(entityManagerFactory.createEntityManager());
 }