Example #1
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;
    }
  }
  private synchronized void checkTimeUpdate(long localTime, long utcTime) throws Exception {
    // broadcast
    _props.setProperty("utc", String.valueOf(utcTime));
    _props.setProperty("local", String.valueOf(localTime));

    TimeUpdateNotification notification =
        new TimeUpdateNotification(TimeUpdateNotification.UPDATE_UTC_TIME, _props);

    Notifier.getInstance().broadcast(notification);

    // wait
    try {
      wait(30000L); // 30 seconds
    } catch (Exception ex) {
    }

    // refreshTimeServer();
    // checkSuccess(_event, _sessions[0], _sm[0], IErrorCode.NO_ERROR);

    long offset = utcTime - localTime;
    Logger.debug("Input UTC Time = " + new Timestamp(utcTime));
    Logger.debug("Input Local Time = " + new Timestamp(localTime));
    Logger.debug("Expected offset: " + offset);

    // check local to utc
    Timestamp ts = TimeUtil.localToUtcTimestamp(_testDate);
    Logger.debug("Converted local to UTc timestamp: " + ts);
    assertEquals("LocalToUtc conversion fail", offset, ts.getTime() - _testDate.getTime());

    // check utc to local
    ts = TimeUtil.utcToLocalTimestamp(_testDate);
    Logger.debug("Converted utc to local timestamp: " + ts);
    assertEquals("UtcToLocal conversion fail", offset, _testDate.getTime() - ts.getTime());
  }
Example #3
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);
     }
   }
 }
  protected void prepareTestData() throws java.lang.Exception {
    long currentTime = TimeUtil.getCurrentLocalTimeMillis();
    long oneHour = 3600000;
    long positive = 8 * oneHour + currentTime;
    long negative = -5 * oneHour + currentTime;

    _times =
        new long[][] {
          {positive, currentTime},
          {currentTime, currentTime},
          {negative, currentTime},
        };

    Calendar cal = GregorianCalendar.getInstance();
    cal.set(2002, 9, 19, 5, 5, 29);
    _testDate = new Timestamp(cal.getTime().getTime());

    Logger.debug("Test date (ts)= " + _testDate);
    Logger.debug("Test date (ms)= " + _testDate.getTime());

    _timeServer = UtcTimeServer.getInstance();

    TimeUtil.setTimeServer(_timeServer);

    _event = new GetUtcTimeEvent();

    //    createSessions(1);
    //    createStateMachines(1);

  }
Example #5
0
  public int update(int oid, String quantity, String memo) { // 更新揀貨單的揀貨數量
    logger.debug(
        "OrderPlaceDDAO.update: "
            + "pickId: "
            + oid
            + ", quantity: "
            + quantity
            + ", memo: "
            + memo);

    EntityManager em = XPersistence.getManager();
    OrderPlaceD bean = em.find(OrderPlaceD.class, oid);
    logger.debug("OrderPlaceD.update: orderPlaceD: " + bean);
    if (bean != null) {
      //			bean.setQuantity(quantity);
      bean.setRemark(memo);
      try {
        em.merge(bean);
        XPersistence.commit();
      } catch (Exception e) {
        logger.error("OrderPlaceD.update: " + e);
      }
      return 1; // 1:成功
    }
    return 0; // 0:失敗
  }
  /**
   * WhiteboardObjectTextJabberImpl constructor.
   *
   * @param xml the XML string object to parse.
   */
  public WhiteboardObjectTextJabberImpl(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      InputStream in = new ByteArrayInputStream(xml.getBytes());
      Document doc = builder.parse(in);

      Element e = doc.getDocumentElement();
      String elementName = e.getNodeName();
      if (elementName.equals("text")) {
        // we have a text
        String id = e.getAttribute("id");
        double x = Double.parseDouble(e.getAttribute("x"));
        double y = Double.parseDouble(e.getAttribute("y"));
        String fill = e.getAttribute("fill");
        String fontFamily = e.getAttribute("font-family");
        int fontSize = Integer.parseInt(e.getAttribute("font-size"));
        String text = e.getTextContent();

        this.setID(id);
        this.setWhiteboardPoint(new WhiteboardPoint(x, y));
        this.setFontName(fontFamily);
        this.setFontSize(fontSize);
        this.setText(text);
        this.setColor(Color.decode(fill).getRGB());
      }
    } catch (ParserConfigurationException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (Exception ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    }
  }
Example #7
0
  @Test
  public void testSum_double_array() {
    logger.info("\ntesting sum(double[] input, int...endPoints)");
    double[] input = null;
    assertEquals(0.0, MathUtil.sum(input), 0.0);
    assertEquals(0.0, MathUtil.sum(input, 0), 0.0);
    assertEquals(0.0, MathUtil.sum(input, 0, 57, 3), 0.0);

    input = new double[] {1.0, 2.0, 3.0, 4.0};
    assertEquals(10.0, MathUtil.sum(input), 0.0);
    assertEquals(3.0, MathUtil.sum(input, 0, 1), 0.0);
    assertEquals(6.0, MathUtil.sum(input, 0, 2), 0.0);
    assertEquals(10.0, MathUtil.sum(input, 0, 3), 0.0);
    assertEquals(10.0, MathUtil.sum(input, 0, 4), 0.0);

    assertEquals(2.0, MathUtil.sum(input, 1, 1), 0.0);
    assertEquals(5.0, MathUtil.sum(input, 1, 2), 0.0);
    assertEquals(9.0, MathUtil.sum(input, 1, 3), 0.0);

    // with indeces out of bounds
    assertEquals(9.0, MathUtil.sum(input, 1, 4), 0.0);
    assertEquals(9.0, MathUtil.sum(input, 4, 1), 0.0);

    input =
        new double[] {
          1.3310000000000004, 1.3310000000000004, 1.3310000000000004, 1.3310000000000004
        };
    double[] cumBins = MathUtil.cumProd(input, true);
    logger.debug(ListArrayUtil.arrayToString(cumBins));
    int regularContribution = 1;
    logger.debug(cumBins[0] + regularContribution * MathUtil.sum(cumBins, 1, cumBins.length - 1));
  }
Example #8
0
 private String parseInclude(InputReader reader) throws InvalidSyntaxException, ParserException {
   String inputFileName = reader.nextWord().asBareString();
   File inputFile = new File(baseDir, inputFileName);
   String statement;
   if (excludeFiles.contains(inputFileName)
       || excludeFiles.contains(inputFile.getAbsolutePath())) {
     // Handle excluded file
     logger.info(reader, "Include file '" + inputFileName + "' omitted being marked as excluded.");
     String outputFileName = MakeBridleNSIS.convertToBridleFilename(inputFileName);
     File outputFile = new File(outDir, outputFileName);
     copyFile(inputFile, outputFile, reader.getLinesRead());
     statement = NSISStatements.include(reader.getIndent(), outputFileName);
   } else if (!inputFile.exists()) {
     // Include file not found
     logger.debug(
         reader, "Include file '" + inputFileName + "' not found, assuming it's found by NSIS.");
     statement = reader.getCurrentStatement();
   } else {
     // Parse include file
     logger.debug(reader, "Follow include: " + inputFile.getAbsolutePath());
     String outputFileName = MakeBridleNSIS.convertToBridleFilename(inputFileName);
     try (BufferedWriter writer = getOutputWriter(outputFileName)) {
       parseFile(inputFile, writer);
     } catch (IOException e) {
       throw new InvalidSyntaxException(e.getMessage(), e);
     }
     statement = NSISStatements.include(reader.getIndent(), outputFileName);
   }
   return statement;
 }
 // Default implementation
 public void setBlock(Player player, World level, Position pos, int mode, int type) {
   logger.debug("Setting block mode {} type {}", mode, type);
   if (mode == 1 && false && !player.isAuthorized(Permission.BUILD)) {
     logger.info("Not permitted to build.");
     try {
       //	player.getSession().getActionSender().sendBlock(pos,
       // level.getBlock(pos),level.getBlockMeta(pos));
     } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   } else if (mode == 0 && false && !player.isAuthorized(Permission.DESTROY)) {
     logger.info("Not permitted to destroy.");
     try {
       //	player.getSession().getActionSender().sendBlock(pos, level.getBlock(pos),
       // level.getBlockMeta(pos));
     } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   } else {
     logger.debug("Building is OK!");
     level.setBlock(pos, (byte) (mode == 1 ? type : 0));
   }
 }
  /**
   * 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;
  }
Example #11
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);
   }
 }
  @Test
  public void testLevels() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    LogPersister.setContext(activity);
    Logger logger = Logger.getLogger("package");
    LogPersister.storeLogs(true);

    final String hi = "hi";

    // no calls should create a file:

    LogPersister.setLogLevel(LEVEL.ERROR);
    logger.warn(hi);
    waitForNotify(logger);
    logger.info(hi);
    waitForNotify(logger);
    logger.debug(hi);
    waitForNotify(logger);

    LogPersister.setLogLevel(LEVEL.WARN);
    logger.info(hi);
    waitForNotify(logger);
    logger.debug(hi);
    waitForNotify(logger);

    LogPersister.setLogLevel(LEVEL.INFO);
    logger.debug(hi);
    waitForNotify(logger);

    // "hi" should not appear in the file

    assertEquals(0, mockFileLogger.getAccumulatedLogCalls().length());
  }
Example #13
0
  @Override
  public boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) {
    try {
      for (Entry<String, String> nativeEntry : platformNativeIndex.entrySet()) {
        if (nativeEntry.getKey().contains(libname)) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Loading mapped entry: [{}] [{}] [{}]",
                libname,
                nativeEntry.getKey(),
                nativeEntry.getValue());
          }
          File nativeLibCopy =
              extractJarEntry(
                  nativeEntry.getValue(),
                  nativeEntry.getKey(),
                  System.getProperty(JAVA_TMP_DIR),
                  String.format("%s.jni", libname));
          System.load(nativeLibCopy.getAbsolutePath());
          return true;
        }
      }
    } catch (Exception e) {
      log.error("Unable to load native library [{}] - {}", libname, e);
    }

    if (log.isDebugEnabled()) {
      log.debug("No mapped library match for [{}]", libname);
    }
    return false;
  }
Example #14
0
 private boolean callgeo(TestConfig conf) throws Exception {
   // logger.debug(conf.toString());
   ByteBuffer wa1 = ByteBuffer.wrap(conf.getInput().getBytes());
   ByteBuffer wa2 = ByteBuffer.allocate(conf.getLengthOfWorkAreaTwo());
   geoclient.callgeo(wa1, wa2);
   String wa1Result = decode(wa1);
   String wa2Result = decode(wa2);
   String rc = getReturnCode(wa1Result);
   String message =
       String.format(
           "Result of %s call:  geosupportReturnCode = \"%s\"", conf.getFunctionName(), rc);
   boolean isSuccess = isSuccess(rc);
   String wa1Msg = String.format("WA1 of %s:", conf.getFunctionName());
   String wa2Msg = String.format("WA2 of %s:", conf.getFunctionName());
   if (isSuccess) {
     logger.debug(message);
     logger.debug(wa1Msg);
     logger.raw(Logger.LEVEL_DEBUG, wa1Result);
     logger.debug(wa2Msg);
     logger.raw(Logger.LEVEL_DEBUG, wa2Result);
   } else {
     logger.error(message);
     logger.error(wa1Msg);
     logger.raw(Logger.LEVEL_ERROR, wa1Result);
     logger.error(wa2Msg);
     logger.raw(Logger.LEVEL_ERROR, wa2Result);
   }
   return isSuccess;
 }
Example #15
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() + ")");
    }
  }
Example #16
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");
    }
  }
Example #17
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;
  }
Example #18
0
 public void execute(String[] filesToModify) throws IOException {
   Logger.debug("Replacing strings in XML data.");
   for (String name : filesToModify) {
     File f = new File(mDataDir, name);
     replaceStringsIn(f);
   }
   Logger.debug("Done with string replacement.");
 }
Example #19
0
 public void dismissCrashAlerts() {
   try {
     new UiWatchers().registerAnrAndCrashWatchers();
     Logger.debug("Registered crash watchers.");
   } catch (Exception e) {
     Logger.debug("Unable to register crash watchers.");
   }
 }
  /**
   * Initializes this network address manager service implementation and starts all
   * processes/threads associated with this address manager, such as a stun firewall/nat detector,
   * keep alive threads, binding lifetime discovery threads and etc. The method may also be used
   * after a call to stop() as a reinitialization technique.
   */
  public void start() {
    // init stun
    String stunAddressStr = null;
    int port = -1;
    stunAddressStr = NetaddrActivator.getConfigurationService().getString(PROP_STUN_SERVER_ADDRESS);
    String portStr = NetaddrActivator.getConfigurationService().getString(PROP_STUN_SERVER_PORT);

    this.localHostFinderSocket = initRandomPortSocket();

    if (stunAddressStr == null || portStr == null) {
      useStun = false;
      // we use the default stun server address only for chosing a public
      // route and not for stun queries.
      stunServerAddress = new StunAddress(DEFAULT_STUN_SERVER_ADDRESS, DEFAULT_STUN_SERVER_PORT);
      logger.info(
          "Stun server address("
              + stunAddressStr
              + ")/port("
              + portStr
              + ") not set (or invalid). Disabling STUN.");

    } else {
      try {
        port = Integer.valueOf(portStr).intValue();
      } catch (NumberFormatException ex) {
        logger.error(portStr + " is not a valid port number. " + "Defaulting to 3478", ex);
        port = 3478;
      }

      stunServerAddress = new StunAddress(stunAddressStr, port);
      detector = new SimpleAddressDetector(stunServerAddress);

      if (logger.isDebugEnabled()) {
        logger.debug(
            "Created a STUN Address detector for the following "
                + "STUN server: "
                + stunAddressStr
                + ":"
                + port);
      }
      detector.start();
      logger.debug("STUN server detector started;");

      // make sure that someone doesn't set invalid stun address and port
      NetaddrActivator.getConfigurationService()
          .addVetoableChangeListener(PROP_STUN_SERVER_ADDRESS, this);
      NetaddrActivator.getConfigurationService()
          .addVetoableChangeListener(PROP_STUN_SERVER_PORT, this);

      // now start a thread query to the stun server and only set the
      // useStun flag to true if it succeeds.
      launchStunServerTest();
    }
  }
Example #21
0
 public static void cleanInodeTableData() throws DotDataException {
   Map map = new HashMap();
   try {
     map = HibernateUtil.getSession().getSessionFactory().getAllClassMetadata();
   } catch (HibernateException e) {
     throw new DotDataException(e.getMessage(), e);
   }
   Iterator it = map.entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry) it.next();
     Class x = (Class) pairs.getKey();
     if (!x.equals(Inode.class)) {
       Object o;
       try {
         o = x.newInstance();
       } catch (Exception e) {
         Logger.info(MaintenanceUtil.class, "Unable to instaniate object");
         Logger.debug(MaintenanceUtil.class, "Unable to instaniate object", e);
         continue;
       }
       if (o instanceof Inode) {
         Inode i = (Inode) o;
         String type = i.getType();
         String tableName =
             ((net.sf.hibernate.persister.AbstractEntityPersister) map.get(x)).getTableName();
         cleanInodeTableData(tableName, type);
       }
     }
   }
   it = map.entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry) it.next();
     Class x = (Class) pairs.getKey();
     if (!x.equals(Inode.class)) {
       Object o;
       try {
         o = x.newInstance();
       } catch (Exception e) {
         Logger.info(MaintenanceUtil.class, "Unable to instaniate object");
         Logger.debug(MaintenanceUtil.class, "Unable to instaniate object", e);
         continue;
       }
       if (o instanceof Inode) {
         Inode i = (Inode) o;
         String type = i.getType();
         String tableName =
             ((net.sf.hibernate.persister.AbstractEntityPersister) map.get(x)).getTableName();
         removeOphanedInodes(tableName, type);
       }
     }
   }
 }
Example #22
0
  @Override
  public <R, E extends Throwable> R doRetryable(
      final IRetryableTask<R, E> task, final IRetryStrategy strategy)
      throws RetryerException, InterruptedException {
    checkArgument(task != null, "task can't be null");
    checkArgument(strategy != null, "strategy can't be null");
    int tryNo = 0;
    final List<Throwable> reasons = Lists.newArrayList();
    MDC.put("task", task.toString());
    try {
      while (true) {
        try {
          log.debug("try #{}...", tryNo);
          if (Thread.interrupted()) {
            throw new InterruptedException("Interrupted on " + tryNo + " try");
          }
          return task.execute(tryNo);
        } catch (InterruptedException e) {
          log.debug("try #{} interrupted: {}", tryNo, e.getMessage());
          throw e;
        } catch (final Throwable reason) {
          log.debug("try #{} failed: {}", tryNo, reason.getMessage());

          reasons.add(reason);

          // cleanup
          if (task.isFatalReason(tryNo, reason)) {
            throw new RetryerException(reasons);
          }

          final RetryInfo retryInfo = strategy.shouldRetry(tryNo, reason);

          if (retryInfo.shouldFail()) {
            throw new RetryerException(reasons);
          } else {
            final long delay = retryInfo.delay();
            if (delay > 0) {
              log.debug("retry after {} ms", delay);
              Thread.sleep(delay);
            } else {
              log.debug("retry now");
            }
          }
        } finally {
          tryNo++;
        }
      }
    } finally {
      MDC.remove("task");
    }
  }
  public void testArticleCountAndType() throws Exception {
    int expCount = 28;
    PluginTestUtil.crawlSimAu(sau);
    String pat1 = "branch(\\d+)/(\\d+file\\.html)";
    String rep1 = "aps/journal/v123/n$1/full/$2";
    PluginTestUtil.copyAu(sau, nau, ".*[^.][^p][^d][^f]$", pat1, rep1);
    String pat2 = "branch(\\d+)/(\\d+file\\.pdf)";
    String rep2 = "aps/journal/v123/n$1/pdf/$2";
    PluginTestUtil.copyAu(sau, nau, ".*\\.pdf$", pat2, rep2);

    // Remove some URLs
    int deleted = 0;
    for (Iterator it = nau.getAuCachedUrlSet().contentHashIterator(); it.hasNext(); ) {
      CachedUrlSetNode cusn = (CachedUrlSetNode) it.next();
      if (cusn instanceof CachedUrl) {
        CachedUrl cu = (CachedUrl) cusn;
        String url = cu.getUrl();
        if (url.contains("/journal/")
            && (url.endsWith("1file.html") || url.endsWith("2file.pdf"))) {
          deleteBlock(cu);
          ++deleted;
        }
      }
    }
    assertEquals(8, deleted);

    Iterator<ArticleFiles> it = nau.getArticleIterator();
    int count = 0;
    int countHtmlOnly = 0;
    int countPdfOnly = 0;
    while (it.hasNext()) {
      ArticleFiles af = it.next();
      log.info(af.toString());
      CachedUrl cu = af.getFullTextCu();
      String url = cu.getUrl();
      assertNotNull(cu);
      String contentType = cu.getContentType();
      log.debug("count " + count + " url " + url + " " + contentType);
      count++;
      if (af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF) == null) {
        ++countHtmlOnly;
      }
      if (af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF) == url) {
        ++countPdfOnly;
      }
    }
    log.debug("Article count is " + count);
    assertEquals(expCount, count);
    assertEquals(4, countHtmlOnly);
    assertEquals(4, countPdfOnly);
  }
Example #24
0
  /** @param args */
  public static void main(String[] args) {
    Set<DomainObject> objectSet = new TreeSet<DomainObject>(new DomainObjectComparator());

    objectSet.add(DomainFactory.createDomainObject("Helga", "Mutter"));
    objectSet.add(DomainFactory.createDomainObject("Walter", "Vater"));
    objectSet.add(DomainFactory.createDomainObject("Hannah", "Tochter1"));
    objectSet.add(DomainFactory.createDomainObject("Paul", "Sohn"));
    objectSet.add(DomainFactory.createDomainObject("Claudia", "Tochter2"));

    for (DomainObject domainObject : objectSet) {
      LOGGER.debug(domainObject.getUuid());
      LOGGER.debug(domainObject.toString());
    }
  }
Example #25
0
  /** @javadoc */
  public void handleChanged(String buildername, int number) {
    // method checks if this really something valid
    // and we should signal a new version

    boolean dirty = false;
    for (VersionCacheWhenNode whennode : whens) {
      List<String> types = whennode.getTypes();

      // check if im known in the types part
      if (types.contains(buildername)) {
        // is there only 1 builder type ?
        if (log.isDebugEnabled()) log.debug("types=" + types.toString());
        if (types.size() == 1) {
          dirty = true;
        } else {
          // so multiple prepare a multilevel !
          List<String> nodes = whennode.getNodes();

          List<String> fields = new Vector<String>();
          fields.add(buildername + ".number");
          List<String> ordervec = new Vector<String>();
          List<String> dirvec = new Vector<String>();

          List<MMObjectNode> vec =
              mmb.getClusterBuilder()
                  .searchMultiLevelVector(
                      nodes,
                      fields,
                      "YES",
                      types,
                      buildername + ".number==" + number,
                      ordervec,
                      dirvec);
          if (log.isDebugEnabled()) log.debug("VEC=" + vec);
          if (vec != null && vec.size() > 0) {
            dirty = true;
          }
        }
      }
    }

    if (dirty) {
      // add one to the version of this counter
      int version = versionnode.getIntValue("version");
      versionnode.setValue("version", version + 1);
      versionnode.commit();
      if (log.isDebugEnabled()) log.debug("Changed = " + (version + 1));
    }
  }
  /**
   * Subscribes this provider as interested in receiving notifications for new mail messages from
   * Google mail services such as Gmail or Google Apps.
   */
  private void subscribeForGmailNotifications() {
    // first check support for the notification service
    String accountIDService = jabberProvider.getAccountID().getService();
    boolean notificationsAreSupported =
        jabberProvider.isFeatureSupported(accountIDService, NewMailNotificationIQ.NAMESPACE);

    if (!notificationsAreSupported) {
      if (logger.isDebugEnabled())
        logger.debug(
            accountIDService
                + " does not seem to provide a Gmail notification "
                + " service so we won't be trying to subscribe for it");
      return;
    }

    if (logger.isDebugEnabled())
      logger.debug(
          accountIDService
              + " seems to provide a Gmail notification "
              + " service so we will try to subscribe for it");

    ProviderManager providerManager = ProviderManager.getInstance();

    providerManager.addIQProvider(
        MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider());
    providerManager.addIQProvider(
        NewMailNotificationIQ.ELEMENT_NAME,
        NewMailNotificationIQ.NAMESPACE,
        new NewMailNotificationProvider());

    Connection connection = jabberProvider.getConnection();

    connection.addPacketListener(new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class));
    connection.addPacketListener(
        new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class));

    if (opSetPersPresence.getCurrentStatusMessage().equals(JabberStatusEnum.OFFLINE)) return;

    // create a query with -1 values for newer-than-tid and
    // newer-than-time attributes
    MailboxQueryIQ mailboxQuery = new MailboxQueryIQ();

    if (logger.isTraceEnabled())
      logger.trace(
          "sending mailNotification for acc: "
              + jabberProvider.getAccountID().getAccountUniqueID());
    jabberProvider.getConnection().sendPacket(mailboxQuery);
  }
Example #27
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());
   }
 }
Example #28
0
  @Test
  public void testDiffRatios() {
    logger.info("\ntesting diffRatios()");
    double[] input = null;
    double[] result = null;
    assertEquals(0, MathUtil.diffRatios(input).length);
    input = new double[] {};
    assertEquals(0, MathUtil.diffRatios(input).length);
    input = new double[] {1};
    assertEquals(0, MathUtil.diffRatios(input).length);

    input = new double[] {1, 2};
    result = MathUtil.diffRatios(input);
    assertEquals(1, result.length);
    assertEquals(2.0, result[0], 0.0);

    input = new double[] {1, 2, 1, 5};
    result = MathUtil.diffRatios(input);
    assertEquals(3, result.length);
    assertEquals(2.0, result[0], 0.0);
    assertEquals(0.5, result[1], 0.0);
    assertEquals(5.0, result[2], 0.0);

    input = new double[] {1, 2, 0, 5, 8};
    result = MathUtil.diffRatios(input);
    logger.debug(ListArrayUtil.arrayToString(result));
    assertEquals(true, Double.isInfinite(result[2]));
    assertEquals(false, Double.isNaN(result[2]));
  }
Example #29
0
  @Test
  public void routesLogMessagesViaSlf4j() {
    Logger logger = Logging.getLogger(LoggingTest.class);

    expectLogMessage(LogLevel.DEBUG, "debug");
    logger.debug("debug");

    expectLogMessage(LogLevel.INFO, "info");
    logger.info("info");

    expectLogMessage(LogLevel.WARN, "warn");
    logger.warn("warn");

    expectLogMessage(LogLevel.LIFECYCLE, "lifecycle");
    logger.lifecycle("lifecycle");

    expectLogMessage(LogLevel.ERROR, "error");
    logger.error("error");

    expectLogMessage(LogLevel.QUIET, "quiet");
    logger.quiet("quiet");

    expectLogMessage(LogLevel.LIFECYCLE, "lifecycle via level");
    logger.log(LogLevel.LIFECYCLE, "lifecycle via level");
  }
Example #30
0
  public static String getDomainNameForColumn(Connector c, Table table, String columnName)
      throws SQLException {
    String schemaName = Helper.getSchemaName(c, table);
    String tableName = table.getName();
    String sql =
        "SELECT domain_name "
            + "FROM information_schema_fuzzy.domains AS D JOIN "
            + "information_schema_fuzzy.columns AS C ON (D.domain_id = C.domain_id) "
            + "WHERE C.table_schema = '"
            + schemaName
            + "' "
            + "AND C.table_name = '"
            + tableName
            + "' "
            + "AND C.column_name = '"
            + columnName
            + "'";

    Logger.debug("Looking for domain name with query:\n" + sql);

    ResultSet rs = c.executeRawQuery(sql);
    SQLException e = null;
    try {
      if (rs.first()) {
        return rs.getString("domain_name");
      }
    } catch (SQLException ex) {
      e = ex;
    }
    throw new SQLException(
        "Domain name not found for " + schemaName + "." + tableName + "." + columnName,
        "42000",
        3020,
        e);
  }