public static boolean copySo(File sourceDir, String so, String dest) {

    try {

      boolean isSuccess = false;

      if (Build.VERSION.SDK_INT >= 21) {
        String[] abis = Build.SUPPORTED_ABIS;
        if (abis != null) {
          for (String abi : abis) {
            LogUtil.d("try supported abi:", abi);
            String name = "lib" + File.separator + abi + File.separator + so;
            File sourceFile = new File(sourceDir, name);
            if (sourceFile.exists()) {
              isSuccess =
                  copyFile(
                      sourceFile.getAbsolutePath(),
                      dest + File.separator + "lib" + File.separator + so);
              // api21 64位系统的目录可能有些不同
              // copyFile(sourceFile.getAbsolutePath(), dest + File.separator +  name);
              break;
            }
          }
        }
      } else {
        LogUtil.d("supported api:", Build.CPU_ABI, Build.CPU_ABI2);

        String name = "lib" + File.separator + Build.CPU_ABI + File.separator + so;
        File sourceFile = new File(sourceDir, name);

        if (!sourceFile.exists() && Build.CPU_ABI2 != null) {
          name = "lib" + File.separator + Build.CPU_ABI2 + File.separator + so;
          sourceFile = new File(sourceDir, name);

          if (!sourceFile.exists()) {
            name = "lib" + File.separator + "armeabi" + File.separator + so;
            sourceFile = new File(sourceDir, name);
          }
        }
        if (sourceFile.exists()) {
          isSuccess =
              copyFile(
                  sourceFile.getAbsolutePath(),
                  dest + File.separator + "lib" + File.separator + so);
        }
      }

      if (!isSuccess) {
        Toast.makeText(
                PluginLoader.getApplicatoin(),
                "安装 " + so + " 失败: NO_MATCHING_ABIS",
                Toast.LENGTH_LONG)
            .show();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return true;
  }
Esempio n. 2
0
 /**
  * 发起GET请求
  *
  * @param link URL
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject get(String link) throws Exception {
   LogUtil.i("HTTP.GET", link);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   // conn.setRequestProperty("User-agent", "Mozilla/5.0 (Linux; Android 4.2.1; Nexus 7
   // Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.GET", token);
   }
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.GET", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
Esempio n. 3
0
  /**
   * 发生Get请求
   *
   * @param url 请求url
   * @return
   * @throws PortalException [参数说明]
   * @return String [返回类型说明]
   * @exception throws [违例类型] [违例说明]
   * @see [类、类#方法、类#成员]
   */
  public String get(String url) {
    GetMethod httpMethod = new GetMethod(url);

    // 设置header信息,传输XML格式的
    httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_UTF_8);

    // 获取响应报文
    String response = null;
    try {
      // 处理响应结果码
      int resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        } else {
          LogUtil.error("Http resultCode=200, but responseBody is empty.");
        }
      } else {
        LogUtil.error("Http resultCode=" + resultCode);
      }
    } catch (Exception ex) {
      LogUtil.error("send http request error.", ex);
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }

    return response;
  }
Esempio n. 4
0
  /** Returns an gzipped copy of the input array. */
  public static final byte[] zip(byte[] in) {
    try {
      // compress using GZIPOutputStream
      ByteArrayOutputStream byteOut =
          new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);

      GZIPOutputStream outStream = new GZIPOutputStream(byteOut);

      try {
        outStream.write(in);
      } catch (Exception e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
      }

      try {
        outStream.close();
      } catch (IOException e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
      }

      return byteOut.toByteArray();

    } catch (IOException e) {
      e.printStackTrace(LogUtil.getWarnStream(LOG));
      return null;
    }
  }
Esempio n. 5
0
  /**
   * 发送http请求,并返回响应的xml报文 <功能详细描述>
   *
   * @param url http请求url
   * @param xml 请求xml报文
   * @return
   */
  private String send(HttpMethod httpMethod) {
    // 获取响应报文
    String response = null;
    int resultCode = HttpStatus.SC_OK;
    try {
      // 设置header信息,传输XML格式的
      httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_UTF_8);

      // 处理响应结果码
      resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        }
      } else {
        response = resultCode + "";
        LogUtil.error("Http response: " + httpMethod.getResponseBodyAsString());
      }
    } catch (Exception ex) {
      response = ex.toString();
      LogUtil.error("send http request error!", ex);
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }
    return response;
  }
Esempio n. 6
0
  /**
   * The FTPServerService must know about all running session threads so they can be terminated on
   * exit. Called when a new session is created.
   */
  protected void registerSessionThread(FtpClientThread newSession) {
    synchronized (this) {
      List<FtpClientThread> toBeRemoved = new ArrayList<FtpClientThread>();
      for (FtpClientThread client : mClientThreads) {
        if (!client.isAlive()) {
          LogUtil.d("Cleaning up finished session...");
          try {
            client.join();
            LogUtil.d("Thread joined");
            toBeRemoved.add(client);
            client.closeSocket();
          } catch (InterruptedException e) {
            LogUtil.d("Interrupted while joining");
          }
        }
      }
      for (FtpClientThread removeThread : toBeRemoved) {
        mClientThreads.remove(removeThread);
      }

      // Cleanup is complete. Now actually add the new thread to the list.
      mClientThreads.add(newSession);
    }
    LogUtil.d("Registered session thread");
  }
Esempio n. 7
0
  /**
   * _more_
   *
   * @return _more_
   */
  public boolean applyProperties() {
    if (dateRangeButton != null) {
      if (dateRangeButton.isSelected()) {
        mode = MODE_ABSDATERANGE;
      } else {
        mode = MODE_COUNT;
      }
    }

    isHiddenOk = getHiddenWidget().isSelected();
    fileCount =
        ((Integer) ((TwoFacedObject) getFileCountWidget().getSelectedItem()).getId()).intValue();
    setFilePath(getFilePathWidget().getText().trim());
    setFilePattern(getPatternWidget().getText().trim());
    setName(getNameWidget().getText().trim());
    setIsActive(getActiveWidget().isSelected());
    try {
      setInterval((long) (new Double(getIntervalWidget().getText().trim()).doubleValue() * 60000));
    } catch (NumberFormatException nfe) {
      LogUtil.userErrorMessage("Bad number format:" + getIntervalWidget().getText());
      return false;
    }
    try {
      setDateRange(
          (long) (new Double(getDateRangeWidget().getText().trim()).doubleValue() * 60000));
    } catch (NumberFormatException nfe) {
      LogUtil.userErrorMessage("Bad number format:" + getDateRangeWidget().getText());
      return false;
    }
    return true;
  }
Esempio n. 8
0
  /**
   * @param filePath
   * @param seek
   * @param length
   * @return
   */
  public static byte[] readFlieToByte(String filePath, int seek, int length) {
    if (TextUtils.isEmpty(filePath)) {
      return null;
    }
    File file = new File(filePath);
    if (!file.exists()) {
      return null;
    }
    if (length == -1) {
      length = (int) file.length();
    }

    try {
      RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
      byte[] bs = new byte[length];
      randomAccessFile.seek(seek);
      randomAccessFile.readFully(bs);
      randomAccessFile.close();
      return bs;
    } catch (Exception e) {
      e.printStackTrace();
      LogUtil.e(
          LogUtil.getLogUtilsTag(FileUtils.class), "readFromFile : errMsg = " + e.getMessage());
      return null;
    }
  }
  private void writeExceptionIntoFile(Throwable ex) {
    String info = null;
    ByteArrayOutputStream bos = null;
    PrintStream printStream = null;
    try {
      bos = new ByteArrayOutputStream();
      printStream = new PrintStream(bos);
      ex.printStackTrace(printStream);
      byte[] data = bos.toByteArray();
      info = new String(data);
      data = null;
      LogUtil.trace(Log.ERROR, TAG, info);

      // kill application
    } catch (Exception e) {
      LogUtil.trace(Log.ERROR, TAG, e.getMessage());
      // kill application
    } finally {
      try {
        if (printStream != null) {
          printStream.close();
        }
        if (bos != null) {
          bos.close();
        }
      } catch (Exception e) {
        // kill application
      }
    }
  }
Esempio n. 10
0
 /**
  * 发起PUT请求
  *
  * @param link URL
  * @param datas 传递给服务器的参数
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject put(String link, Object datas) throws Exception {
   LogUtil.i("HTTP.PUT", link);
   //        StringBuffer data = new StringBuffer();
   //        if (datas != null) {
   //            Iterator<Map.Entry<String, Object>> it = datas.entrySet().iterator();
   //            while (it.hasNext()) {
   //                Map.Entry<String, Object> pairs = it.next();
   //                if (pairs.getValue() instanceof Object[]) {
   //                    for (Object d : (Object[]) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else if (pairs.getValue() instanceof Collection) {
   //                    for (Object d : (Collection) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else {
   //                    data.append("&" + pairs.getKey() + "=" + pairs.getValue().toString());
   //                }
   //            }
   //        }
   String data = "";
   if (datas instanceof Map) {
     JSONObject json = new JSONObject((Map) datas);
     data = json.toString();
   } else if (datas instanceof JSONObject) {
     data = datas.toString();
   }
   LogUtil.i("HTTP.PUT", data);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("PUT");
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.PUT", token);
   }
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   OutputStream out = conn.getOutputStream();
   out.write(data.getBytes());
   out.flush();
   out.close();
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.PUT", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
 public static void init() throws IOException {
   String fileName = LogUtil.caluFileName(Log2FileConf.errRecordDir, Log2FileConf.errFileName);
   File file = LogUtil.getLogFile(fileName, false);
   while (file.exists()) {
     fileName = fileName + ".bak";
     file = new File(fileName);
   }
   currFileName = fileName;
   bfw = LogUtil.getNewBufferedWriter(fileName);
 }
Esempio n. 12
0
  /**
   * createExcelWithTemplate.
   *
   * @param inputStream
   * @param os
   * @param props
   * @param dataList
   */
  @SuppressWarnings("rawtypes")
  public void createExcelWithTemplate(
      InputStream inputStream, OutputStream os, List<String> props, List dataList) {
    Workbook tBook = null;
    WritableWorkbook wbook = null;
    // 需要导出的属性名getter
    List<String> getterList = new ArrayList<String>();

    try {
      tBook = Workbook.getWorkbook(inputStream);
      WorkbookSettings settings = new WorkbookSettings();
      settings.setWriteAccess(null);
      wbook = Workbook.createWorkbook(os, tBook, settings);
      WritableSheet wsheet = wbook.getSheet(0);
      if (props != null) {
        for (String prop : props) {
          getterList.add("get" + prop.substring(0, 1).toUpperCase() + prop.substring(1));
        }
      }
      int row = 1;
      int size = getterList.size();
      if (dataList != null) {
        for (Object obj : dataList) {
          int col = 0;
          Class clazz = obj.getClass();

          for (int i = 0; i < size; i++) {
            Method method = BeanUtils.findMethod(clazz, getterList.get(i), new Class[0]);
            Object valObj = method.invoke(obj, new Object[0]);
            addCell(wsheet, col++, row, valObj);
          }
          row++;
        }
      }
      // 输出内容
      wbook.write();
    } catch (Exception e) {
      logger.error(LogUtil.parserBean(props) + LogUtil.parserBean(dataList), e);
    } finally {
      if (wbook != null) {
        try {
          wbook.close();
        } catch (Exception e) {
          logger.error(e);
        }
      }
      if (tBook != null) {
        try {
          tBook.close();
        } catch (Exception e) {
          logger.error(e);
        }
      }
    }
  }
 private static BufferedWriter getBufferedWriter() throws IOException {
   String fileName = LogUtil.caluFileName(Log2FileConf.errRecordDir, Log2FileConf.errFileName);
   if (fileName.split("\\.")[1].equals(currFileName.split("\\.")[1])) {
     return bfw;
   }
   bfw.flush();
   bfw.close();
   currFileName = fileName;
   bfw = LogUtil.getNewBufferedWriter(currFileName);
   return bfw;
 }
 /** 使用Gson解析服务器返回的JSON数据,并将解析的数据存储到本地 */
 public static void handleWeatherResponse(Context context, String response) {
   try {
     LogUtil.i("UTILITY", "----------------->" + response.toString());
     Gson gson = new Gson();
     Weather weather = gson.fromJson(response, Weather.class);
     LogUtil.i("UTILITY", "----------------->" + weather.toString());
     Weatherinfo info = weather.getWeatherinfo();
     LogUtil.i("UTILITY", "----------------->" + info.toString());
     saveWeatherInfo(context, info);
   } catch (Exception e) {
     // TODO: handle exception
   }
 }
Esempio n. 15
0
  public static Bitmap getSuitableBitmap(String filePath) {
    if (TextUtils.isEmpty(filePath)) {
      LogUtil.e(TAG, "filepath is null or nil");
      return null;
    }

    if (!new File(filePath).exists()) {
      LogUtil.e(TAG, "getSuitableBmp fail, file does not exist, filePath = " + filePath);
      return null;
    }
    try {

      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      Bitmap decodeFile = BitmapFactory.decodeFile(filePath, options);
      if (decodeFile != null) {
        decodeFile.recycle();
      }

      if ((options.outWidth <= 0) || (options.outHeight <= 0)) {
        LogUtil.e(TAG, "get bitmap fail, file is not a image file = " + filePath);
        return null;
      }

      int maxWidth = 960;
      int width = 0;
      int height = 0;
      if ((options.outWidth <= options.outHeight * 2.0D) && options.outWidth > 480) {
        height = maxWidth;
        width = options.outWidth;
      }
      if ((options.outHeight <= options.outWidth * 2.0D) || options.outHeight <= 480) {
        width = maxWidth;
        height = options.outHeight;
      }

      Bitmap bitmap = extractThumbNail(filePath, width, height, false);
      if (bitmap == null) {
        LogUtil.e(TAG, "getSuitableBmp fail, temBmp is null, filePath = " + filePath);
        return null;
      }
      int degree = readPictureDegree(filePath);
      if (degree != 0) {
        bitmap = degreeBitmap(bitmap, degree);
      }
      return bitmap;
    } catch (Exception e) {
      LogUtil.e(TAG, "decode bitmap err: " + e.getMessage());
      return null;
    }
  }
Esempio n. 16
0
 boolean setLock(String rw, long beginIndex, long bytesNum, boolean s) {
   if (!this.exists()) return false;
   try {
     raf = new RandomAccessFile(this, rw);
     fc = raf.getChannel();
     flk = fc.lock(beginIndex, bytesNum, s);
   } catch (OverlappingFileLockException oe) {
     LogUtil.warn("[SetLock]", "[No effect]", "the region has already been locked");
     return false;
   } catch (Exception e) {
     LogUtil.info("[SetLock]", "[No effect]", e);
     return false;
   }
   return true;
 }
Esempio n. 17
0
  /**
   * Implementation of getConnection() methods. Gets connection from either java.sql.DriverManager,
   * or from IConnectionFactory defined in the extension
   */
  private synchronized Connection doConnect(
      String driverClass,
      String url,
      String jndiNameUrl,
      Properties connectionProperties,
      Collection<String> driverClassPath)
      throws SQLException, OdaException {
    // JNDI should take priority when getting connection.If JNDI Data Source
    // URL is defined, try use name service to get connection
    Connection jndiDSConnection =
        getJndiDSConnection(driverClass, jndiNameUrl, connectionProperties);

    if (jndiDSConnection != null) // successful
    return jndiDSConnection; // done

    IConnectionFactory factory = getDriverConnectionFactory(driverClass);
    if (factory != null) {
      // Use connection factory for connection
      if (logger.isLoggable(Level.FINER))
        logger.finer(
            "Calling IConnectionFactory.getConnection. driverClass="
                + driverClass
                + //$NON-NLS-1$
                ", url="
                + LogUtil.encryptURL(url)); // $NON-NLS-1$
      return factory.getConnection(driverClass, url, connectionProperties);
    }

    // no driverinfo extension for driverClass connectionFactory
    // no JNDI Data Source URL defined, or
    // not able to get a JNDI data source connection,
    // use the JDBC DriverManager instead to get a JDBC connection
    loadAndRegisterDriver(driverClass, driverClassPath);
    if (logger.isLoggable(Level.FINER))
      logger.finer(
          "Calling DriverManager.getConnection. url=" + LogUtil.encryptURL(url)); // $NON-NLS-1$
    try {
      return DriverManager.getConnection(url, connectionProperties);
    } catch (Exception e) {
      registerDriver(driverClass, null, true, true);
      try {
        return DriverManager.getConnection(url, connectionProperties);
      } catch (Exception ex) {
        throw new JDBCException(
            ResourceConstants.CONN_GET_ERROR, null, truncate(ex.getLocalizedMessage()));
      }
    }
  }
Esempio n. 18
0
  /**
   * Notifies the request queue that this request has finished (successfully or with error).
   *
   * <p>Also dumps all events from this request's event log; for debugging.
   */
  void finish(final String tag) {
    if (mRequestQueue != null) {
      mRequestQueue.finish(this);
    }
    if (MarkerLog.ENABLED) {
      final long threadId = Thread.currentThread().getId();
      if (Looper.myLooper() != Looper.getMainLooper()) {
        // If we finish marking off of the main thread, we need to
        // actually do it on the main thread to ensure correct ordering.
        Handler mainThread = new Handler(Looper.getMainLooper());
        mainThread.post(
            new Runnable() {
              @Override
              public void run() {
                mEventLog.add(tag, threadId);
                mEventLog.finish(this.toString());
              }
            });
        return;
      }

      mEventLog.add(tag, threadId);
      mEventLog.finish(this.toString());
    } else {
      long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;
      if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {
        LogUtil.d("%d ms: %s", requestTime, this.toString());
      }
    }
  }
Esempio n. 19
0
 /**
  * 显示Response消息
  *
  * @param connection
  * @param CharsetName
  * @return
  * @throws URISyntaxException
  * @throws IOException
  */
 private String response(final HttpURLConnection connection, String encoding)
     throws URISyntaxException, IOException, Exception {
   InputStream in = null;
   StringBuilder sb = new StringBuilder(1024);
   BufferedReader br = null;
   try {
     if (200 == connection.getResponseCode()) {
       in = connection.getInputStream();
       sb.append(new String(read(in), encoding));
     } else {
       in = connection.getErrorStream();
       sb.append(new String(read(in), encoding));
     }
     LogUtil.writeLog("HTTP Return Status-Code:[" + connection.getResponseCode() + "]");
     return sb.toString();
   } catch (Exception e) {
     throw e;
   } finally {
     if (null != br) {
       br.close();
     }
     if (null != in) {
       in.close();
     }
     if (null != connection) {
       connection.disconnect();
     }
   }
 }
Esempio n. 20
0
 /**
  * @param args
  * @throws ParseException
  * @throws UnknownHostException
  */
 public static void main(String[] args) throws ParseException, UnknownHostException {
   LogUtil.getInstance().init("logclient.properties");
   for (int i = 0; i < 100; i++) {
     //			LogUtil.getInstance().log(3, "Leon"+i, InetAddress.getLocalHost().getHostAddress(), 1,
     // new Date(), "xxxxx");
   }
 }
 private int GetIntentId() {
   int val = dataStore.getInt("intentId", 0);
   dataEditor.putInt("intentId", val + 1);
   dataEditor.commit();
   LogUtil.LogString("send id");
   return val;
 }
Esempio n. 22
0
  public static Map<String, Object> getStringPlace(String json) {
    Map<String, Object> res = new HashMap<String, Object>();

    try {
      SubjectVo mSV = new SubjectVo();
      JSONObject objItem = new JSONObject(json);
      String subjectname = objItem.getString("subjectname");
      String subjectid = objItem.getString("subjectid");
      mSV.setSubjectId(subjectid);
      mSV.setSubjectName(subjectname);
      res.put("sv", mSV);
      String[] id = null;
      String[] name = null;
      JSONArray classList = objItem.getJSONArray("classlist");
      if (classList != null && classList.length() > 0) {
        id = new String[classList.length()];
        name = new String[classList.length()];
        for (int i = 0; i < classList.length(); i++) {
          JSONObject classItem = (JSONObject) classList.get(i);
          String classid = classItem.getString("classid");
          String schoollocation = classItem.getString("schoollocation");
          name[i] = schoollocation;
          id[i] = classid;
          LogUtil.d("&&&&&&&", schoollocation + "  classid : " + classid);
        }
        res.put("name", name);
        res.put("id", id);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return res;
  }
 /**
  * This method gets the applicable providers that meet the search criteria. If none available, the
  * search result will be empty.
  *
  * @param criteria the search criteria
  * @return the search result with the matched providers
  * @throws IllegalArgumentException if the criteria is null
  * @throws IllegalArgumentException if criteria.pageNumber < 0
  * @throws IllegalArgumentException - if criteria.pageSize < 1 unless criteria.pageNumber <= 0
  * @throws ServiceException for any other exceptions encountered
  */
 @TransactionAttribute(TransactionAttributeType.REQUIRED)
 public SearchResult<ProviderProfile> search(HospiceSearchCriteria criteria)
     throws ServiceException {
   String signature = CLASS_NAME + "#search(HospiceSearchCriteria criteria)";
   LogUtil.traceEntry(getLog(), signature, new String[] {"criteria"}, new Object[] {criteria});
   try {
     SearchResult<ProviderProfile> results = hospiceLicensingDAO.search(criteria);
     return LogUtil.traceExit(getLog(), signature, results);
   } catch (IllegalArgumentException e) {
     LogUtil.traceError(getLog(), signature, e);
     throw e;
   } catch (ServiceException e) {
     LogUtil.traceError(getLog(), signature, e);
     throw e;
   }
 }
Esempio n. 24
0
 public static NotificationVo getStringToObj(String jArr, NotificationVo nv) {
   NotificationVo result = nv;
   try {
     LogUtil.d(TAG, "json :---------" + jArr.toString());
     JSONObject objJson = new JSONObject(jArr);
     String msgType = objJson.getString("msg_type");
     String msgId = objJson.getString("msgId");
     String msgClassName = objJson.getString("msgClassName");
     String msgFromClassName = objJson.getString("mfcName");
     boolean isPing = objJson.getBoolean("isPing");
     boolean isShock = objJson.getBoolean("isShock");
     String msgc = objJson.getString("msg_c");
     if ("2".equals(msgType)) {
       String msgToType = objJson.getString("msgToType");
       String strData = objJson.getString("strData");
       result.setStrData(strData);
       result.setMsgToType(msgToType);
     } else {
       String openUrl = objJson.getString("open_url");
       nv.setOpenUrl(openUrl);
     }
     result.setMsgId(msgId);
     result.setMsgClassName(msgClassName);
     result.setMsgFromClassName(msgFromClassName);
     result.setMsgType(msgType);
     result.setPing(isPing);
     result.setShock(isShock);
     result.setMsgC(msgc);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return result;
 }
  public static void rewriteRValues(ClassLoader cl, String packageName, int id) {
    final Class<?> rClazz;
    try {
      rClazz = cl.loadClass(packageName + ".R");
    } catch (ClassNotFoundException e) {
      LogUtil.d("No resource references to update in package " + packageName);
      return;
    }

    final Method callback;
    try {
      callback = rClazz.getMethod("onResourcesLoaded", int.class);
    } catch (NoSuchMethodException e) {
      // No rewriting to be done.
      return;
    }

    Throwable cause;
    try {
      callback.invoke(null, id);
      return;
    } catch (IllegalAccessException e) {
      cause = e;
    } catch (InvocationTargetException e) {
      cause = e.getCause();
    }

    throw new RuntimeException("Failed to rewrite resource references for " + packageName, cause);
  }
public class ImageUtil {
  private static final Logger logger = LogUtil.getLogger(ImageUtil.class);

  /** fileName capture screen shot */
  public static void captureScreenshot(WebDriver driver, String fileName) {
    String screenshotPath = System.getProperty("user.dir") + File.separator + "screenshot";
    if (!new File(screenshotPath).exists()) {
      new File(screenshotPath).mkdir();
    }
    // Add date and time in current picture file name
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
    String currentDateTime = sdf.format(new Date());
    fileName = fileName + "-" + currentDateTime;
    String imagePath = screenshotPath + File.separator + fileName + ".png";
    try {
      String base64Screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
      byte[] decodedScreenshot = Base64.decodeBase64(base64Screenshot.getBytes());
      File imageFile = new File(imagePath);
      if (!imageFile.exists()) {
        if (imageFile.createNewFile()) {
          logger.debug("New File: " + imageFile.getName() + " has been created!");
        }
      }
      FileOutputStream fos = new FileOutputStream(imageFile);
      fos.write(decodedScreenshot);
      fos.close();
      logger.debug("Put screen shot to " + imagePath);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Esempio n. 27
0
 /**
  * "2014-12-22 21:31:32"
  *
  * @return
  */
 public static String getData_yyyy_MM_dd_hh_mm_ss() {
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   Date curDate = new Date(System.currentTimeMillis()); // 获取当前时间
   String str = formatter.format(curDate);
   LogUtil.Log(tag, "getData_yyyy_MM_dd_hh_mm_ss = " + str);
   return str;
 }
/**
 * A broadcast receiver to handle the changes in network connectiion states.
 *
 * <p><<<<<<< HEAD
 *
 * @author Sehwan Noh ([email protected]) 192.168.0
 *     <p>=======
 * @author Sehwan Noh ([email protected]) >>>>>>> origin/master
 */
public class ConnectivityReceiver extends BroadcastReceiver {

  private static final String LOGTAG = LogUtil.makeLogTag(ConnectivityReceiver.class);

  private ConnectService connectionService;

  public ConnectivityReceiver(ConnectService connectionService) {
    this.connectionService = connectionService;
  }

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(LOGTAG, "ConnectivityReceiver.onReceive()...");
    String action = intent.getAction();
    Log.d(LOGTAG, "action=" + action);

    ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if (networkInfo != null) {
      Log.d(LOGTAG, "Network Type  = " + networkInfo.getTypeName());
      Log.d(LOGTAG, "Network State = " + networkInfo.getState());
      if (networkInfo.isConnected()) {
        Log.i(LOGTAG, "Network connected");
        connectionService.connect();
      }
    } else {
      Log.e(LOGTAG, "Network unavailable");
      connectionService.disconnect();
    }
  }
}
Esempio n. 29
0
 /**
  * 将Map存储的对象,转换为key=value&key=value的字符
  *
  * @param requestParam
  * @param coder
  * @return
  */
 private String getRequestParamString(Map<String, String> requestParam, String coder) {
   if (null == coder || "".equals(coder)) {
     coder = "UTF-8";
   }
   StringBuffer sf = new StringBuffer("");
   String reqstr = "";
   if (null != requestParam && 0 != requestParam.size()) {
     for (Entry<String, String> en : requestParam.entrySet()) {
       try {
         sf.append(
             en.getKey()
                 + "="
                 + (null == en.getValue() || "".equals(en.getValue())
                     ? ""
                     : URLEncoder.encode(en.getValue(), coder))
                 + "&");
       } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
         return "";
       }
     }
     reqstr = sf.substring(0, sf.length() - 1);
   }
   LogUtil.writeLog("请求报文(已做过URLEncode编码):[" + reqstr + "]");
   return reqstr;
 }
  public static void readFileFromJar(String jarFilePath, String metaInfo) {
    LogUtil.d("readFileFromJar:", jarFilePath, metaInfo);
    JarFile jarFile = null;
    try {
      jarFile = new JarFile(jarFilePath);
      JarEntry entry = jarFile.getJarEntry(metaInfo);
      if (entry != null) {
        InputStream input = jarFile.getInputStream(entry);

        return;
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (jarFile != null) {
        try {
          jarFile.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return;
  }