public static void scheduleJobAction(PortletRequest request, String action)
      throws SchedulerException, ParseException {
    // Checking all the rows to see which are selected
    String rowSelection;
    for (int i = 0;
        (rowSelection = request.getParameter(PARAMETER_JOB_SELECTED + i)) != null;
        i++) {
      boolean rowSelected = GetterUtil.get(rowSelection, false);
      if (rowSelected) {

        String jobName = ParamUtil.getString(request, PARAMETER_JOB_NAME + i);
        String groupName = ParamUtil.getString(request, PARAMETER_JOB_GROUP + i);
        String storageTypeText = ParamUtil.getString(request, PARAMETER_STORAGE_TYPE + i);
        StorageType storageType = StorageType.valueOf(storageTypeText);

        // Log debug messages
        if (_log.isDebugEnabled()) {
          _log.debug(
              String.format(
                  LOG_JOB_FORMAT, action, LOG_ACTION_MSG, jobName, groupName, storageType));
        }

        if (action.equals(ACTION_PAUSE)) {
          SchedulerEngineHelperUtil.pause(jobName, groupName, storageType);
        } else if (action.equals(ACTION_RESUME)) {
          SchedulerEngineHelperUtil.resume(jobName, groupName, storageType);
        } else if (action.equals(ACTION_RUN)) {
          runScheduledJob(jobName, groupName);
        }
      }
    }
  }
  public static String get(HttpServletRequest request, String param, String defaultValue) {

    String returnValue = GetterUtil.get(request.getParameter(param), defaultValue);

    if (returnValue != null) {
      return returnValue.trim();
    }

    return null;
  }
  public static String get(ServiceContext serviceContext, String param, String defaultValue) {

    String returnValue = GetterUtil.get(serviceContext.getAttribute(param), defaultValue);

    if (returnValue != null) {
      return returnValue.trim();
    }

    return null;
  }
  public static float get(PortletRequest portletRequest, String param, float defaultValue) {

    return GetterUtil.get(portletRequest.getParameter(param), defaultValue);
  }
  public static Date get(
      PortletRequest portletRequest, String param, DateFormat dateFormat, Date defaultValue) {

    return GetterUtil.get(portletRequest.getParameter(param), dateFormat, defaultValue);
  }
  public static boolean get(PortletRequest portletRequest, String param, boolean defaultValue) {

    return GetterUtil.get(portletRequest.getParameter(param), defaultValue);
  }
  public static short get(HttpServletRequest request, String param, short defaultValue) {

    return GetterUtil.get(request.getParameter(param), defaultValue);
  }
  public static short get(ServiceContext serviceContext, String param, short defaultValue) {

    return GetterUtil.get(serviceContext.getAttribute(param), defaultValue);
  }
  public static Date get(
      ServiceContext serviceContext, String param, DateFormat dateFormat, Date defaultValue) {

    return GetterUtil.get(serviceContext.getAttribute(param), dateFormat, defaultValue);
  }
Exemplo n.º 10
0
/** @author Amos Fong */
public class LicenseUtil {

  public static final String LICENSE_REPOSITORY_DIR =
      PropsValues.LIFERAY_HOME.concat("/data/license");

  public static final String LICENSE_SERVER_URL =
      GetterUtil.get(PropsUtil.get("license.server.url"), "https://www.liferay.com");

  public static Map<String, String> getClusterServerInfo(String clusterNodeId) throws Exception {

    List<ClusterNode> clusterNodes = ClusterExecutorUtil.getClusterNodes();

    ClusterNode clusterNode = null;

    for (ClusterNode curClusterNode : clusterNodes) {
      String curClusterNodeId = curClusterNode.getClusterNodeId();

      if (curClusterNodeId.equals(clusterNodeId)) {
        clusterNode = curClusterNode;

        break;
      }
    }

    if (clusterNode == null) {
      return null;
    }

    try {
      if (clusterNode.equals(ClusterExecutorUtil.getLocalClusterNode())) {
        return getServerInfo();
      }

      ClusterRequest clusterRequest =
          ClusterRequest.createUnicastRequest(_getServerInfoMethodHandler, clusterNodeId);

      FutureClusterResponses futureClusterResponses = ClusterExecutorUtil.execute(clusterRequest);

      ClusterNodeResponses clusterNodeResponses =
          futureClusterResponses.get(20000, TimeUnit.MILLISECONDS);

      ClusterNodeResponse clusterNodeResponse =
          clusterNodeResponses.getClusterResponse(clusterNode);

      return (Map<String, String>) clusterNodeResponse.getResult();
    } catch (Exception e) {
      _log.error(e, e);

      throw e;
    }
  }

  public static String getHostName() {
    if (_hostName == null) {
      _hostName = StringPool.BLANK;

      try {
        Runtime runtime = Runtime.getRuntime();

        Process process = runtime.exec("hostname");

        BufferedReader bufferedReader =
            new BufferedReader(new InputStreamReader(process.getInputStream()), 128);

        _hostName = bufferedReader.readLine();

        bufferedReader.close();
      } catch (Exception e) {
        _log.error("Unable to read local server's host name");

        _log.error(e, e);
      }
    }

    return _hostName;
  }

  public static Set<String> getIpAddresses() {
    if (_ipAddresses == null) {
      _ipAddresses = new HashSet<String>();

      try {
        List<NetworkInterface> networkInterfaces =
            Collections.list(NetworkInterface.getNetworkInterfaces());

        for (NetworkInterface networkInterface : networkInterfaces) {
          List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses());

          for (InetAddress inetAddress : inetAddresses) {
            if (inetAddress.isLinkLocalAddress()
                || inetAddress.isLoopbackAddress()
                || !(inetAddress instanceof Inet4Address)) {

              continue;
            }

            _ipAddresses.add(inetAddress.getHostAddress());
          }
        }
      } catch (Exception e) {
        _log.error("Unable to read local server's IP addresses");

        _log.error(e, e);
      }
    }

    return new HashSet<String>(_ipAddresses);
  }

  public static Set<String> getMacAddresses() {
    if (_macAddresses != null) {
      return new HashSet<String>(_macAddresses);
    }

    Set<String> macAddresses = new HashSet<String>();

    String osName = System.getProperty("os.name");

    String executable = null;
    String arguments = null;

    if (StringUtil.startsWith(osName, "win")) {
      executable = "ipconfig";
      arguments = "/all";
    } else {
      if (StringUtil.startsWith(osName, "aix")) {
        executable = "netstat";
        arguments = "-ina";
      } else {
        executable = "ifconfig";
        arguments = "-a";
      }

      File sbinDir = new File("/sbin", executable);

      if (sbinDir.exists()) {
        executable = "/sbin/".concat(executable);
      }
    }

    try {
      Runtime runtime = Runtime.getRuntime();

      Process process = runtime.exec(new String[] {executable, arguments});

      macAddresses = getMacAddresses(osName, process.getInputStream());
    } catch (Exception e) {
      _log.error(e, e);
    }

    _macAddresses = macAddresses;

    return new HashSet<String>(macAddresses);
  }

  public static Set<String> getMacAddresses(String osName, InputStream processInputStream)
      throws Exception {

    Set<String> macAddresses = new HashSet<String>();

    Pattern macAddressPattern = _macAddressPattern1;

    if (StringUtil.startsWith(osName, "aix")) {
      macAddressPattern = _macAddressPattern2;
    }

    String processOutput = StringUtil.read(processInputStream);

    String[] lines = StringUtil.split(processOutput, CharPool.NEW_LINE);

    for (String line : lines) {
      Matcher matcher = macAddressPattern.matcher(line);

      if (!matcher.find()) {
        continue;
      }

      String macAddress = matcher.group(1);

      macAddress = macAddress.toLowerCase();
      macAddress = macAddress.replace(CharPool.DASH, CharPool.COLON);
      macAddress = macAddress.replace(CharPool.PERIOD, CharPool.COLON);

      StringBuilder sb = new StringBuilder(17);

      sb.append(macAddress);

      for (int i = 1; i < 5; ++i) {
        int pos = (i * 3) - 1;

        if (sb.charAt(pos) != CharPool.COLON) {
          sb.insert((i - 1) * 3, CharPool.NUMBER_0);
        }
      }

      if (sb.length() < 17) {
        sb.insert(15, CharPool.NUMBER_0);
      }

      macAddress = sb.toString();

      macAddresses.add(macAddress);
    }

    return macAddresses;
  }

  public static byte[] getServerIdBytes() throws Exception {
    if (_serverIdBytes != null) {
      return _serverIdBytes;
    }

    File serverIdFile = new File(LICENSE_REPOSITORY_DIR + "/server/serverId");

    if (!serverIdFile.exists()) {
      return new byte[0];
    }

    _serverIdBytes = FileUtil.getBytes(serverIdFile);

    return _serverIdBytes;
  }

  public static Map<String, String> getServerInfo() {
    Map<String, String> serverInfo = new HashMap<String, String>();

    serverInfo.put("hostName", getHostName());
    serverInfo.put("ipAddresses", StringUtil.merge(getIpAddresses()));
    serverInfo.put("macAddresses", StringUtil.merge(getMacAddresses()));

    return serverInfo;
  }

  public static void registerOrder(HttpServletRequest request) {
    String orderUuid = ParamUtil.getString(request, "orderUuid");
    String productEntryName = ParamUtil.getString(request, "productEntryName");
    int maxServers = ParamUtil.getInteger(request, "maxServers");

    List<ClusterNode> clusterNodes = ClusterExecutorUtil.getClusterNodes();

    if ((clusterNodes.size() <= 1)
        || Validator.isNull(productEntryName)
        || Validator.isNull(orderUuid)) {

      Map<String, Object> attributes = registerOrder(orderUuid, productEntryName, maxServers);

      for (Map.Entry<String, Object> entry : attributes.entrySet()) {
        request.setAttribute(entry.getKey(), entry.getValue());
      }
    } else {
      for (ClusterNode clusterNode : clusterNodes) {
        boolean register =
            ParamUtil.getBoolean(request, clusterNode.getClusterNodeId() + "_register");

        if (!register) {
          continue;
        }

        try {
          _registerClusterOrder(request, clusterNode, orderUuid, productEntryName, maxServers);
        } catch (Exception e) {
          _log.error(e, e);

          InetAddress inetAddress = clusterNode.getInetAddress();

          String message = "Error contacting " + inetAddress.getHostName();

          if (clusterNode.getPort() != -1) {
            message += StringPool.COLON + clusterNode.getPort();
          }

          request.setAttribute(clusterNode.getClusterNodeId() + "_ERROR_MESSAGE", message);
        }
      }
    }
  }

  public static Map<String, Object> registerOrder(
      String orderUuid, String productEntryName, int maxServers) {

    Map<String, Object> attributes = new HashMap<String, Object>();

    if (Validator.isNull(orderUuid)) {
      return attributes;
    }

    try {
      JSONObject jsonObject = _createRequest(orderUuid, productEntryName, maxServers);

      String response = sendRequest(jsonObject.toString());

      JSONObject responseJSONObject = JSONFactoryUtil.createJSONObject(response);

      attributes.put("ORDER_PRODUCT_ID", responseJSONObject.getString("productId"));
      attributes.put("ORDER_PRODUCTS", _getOrderProducts(responseJSONObject));

      String errorMessage = responseJSONObject.getString("errorMessage");

      if (Validator.isNotNull(errorMessage)) {
        attributes.put("ERROR_MESSAGE", errorMessage);

        return attributes;
      }

      String licenseXML = responseJSONObject.getString("licenseXML");

      if (Validator.isNotNull(licenseXML)) {
        LicenseManagerUtil.registerLicense(responseJSONObject);

        attributes.clear();
        attributes.put("SUCCESS_MESSAGE", "Your license has been successfully registered.");
      }
    } catch (Exception e) {
      _log.error(e, e);

      attributes.put("ERROR_MESSAGE", "There was an error contacting " + LICENSE_SERVER_URL);
    }

    return attributes;
  }

  public static String sendRequest(String request) throws Exception {
    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
      String serverURL = LICENSE_SERVER_URL;

      if (!serverURL.endsWith(StringPool.SLASH)) {
        serverURL += StringPool.SLASH;
      }

      serverURL += "osb-portlet/license";

      URL url = new URL(serverURL);

      URLConnection connection = null;

      if (Validator.isNotNull(_PROXY_URL)) {
        if (_log.isInfoEnabled()) {
          _log.info("Using proxy " + _PROXY_URL + StringPool.COLON + _PROXY_PORT);
        }

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(_PROXY_URL, _PROXY_PORT));

        connection = url.openConnection(proxy);

        if (Validator.isNotNull(_PROXY_USER_NAME)) {
          String login = _PROXY_USER_NAME + StringPool.COLON + _PROXY_PASSWORD;

          String encodedLogin = Base64.encode(login.getBytes());

          connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
        }
      } else {
        connection = url.openConnection();
      }

      connection.setDoOutput(true);

      outputStream = connection.getOutputStream();

      outputStream.write(_encryptRequest(serverURL, request));

      String response = _decryptResponse(serverURL, connection.getInputStream());

      if (_log.isDebugEnabled()) {
        _log.debug("Server response: " + response);
      }

      if (Validator.isNull(response)) {
        throw new Exception("Server response is null");
      }

      return response;
    } finally {
      try {
        if (inputStream != null) {
          inputStream.close();
        }
      } catch (Exception e) {
      }

      try {
        if (outputStream != null) {
          outputStream.close();
        }
      } catch (Exception e) {
      }
    }
  }

  public static void writeServerProperties(byte[] serverIdBytes) throws Exception {

    File serverIdFile = new File(LICENSE_REPOSITORY_DIR + "/server/serverId");

    FileUtil.write(serverIdFile, serverIdBytes);
  }

  private static JSONObject _createRequest(
      String orderUuid, String productEntryName, int maxServers) throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    jsonObject.put("version", 2);
    jsonObject.put("orderUuid", orderUuid);
    jsonObject.put("liferayVersion", ReleaseInfo.getBuildNumber());

    if (Validator.isNull(productEntryName)) {
      jsonObject.put("cmd", "QUERY");
    } else {
      jsonObject.put("cmd", "REGISTER");

      if (productEntryName.startsWith("basic")) {
        jsonObject.put("productEntryName", "basic");

        if (productEntryName.equals("basic-cluster")) {
          jsonObject.put("cluster", true);
          jsonObject.put("maxServers", maxServers);
        } else if (productEntryName.startsWith("basic-")) {
          String[] productNameArray = StringUtil.split(productEntryName, StringPool.DASH);

          if (productNameArray.length >= 3) {
            jsonObject.put("offeringEntryId", productNameArray[1]);
            jsonObject.put("clusterId", productNameArray[2]);
          }
        }
      } else {
        jsonObject.put("productEntryName", productEntryName);
      }

      jsonObject.put("hostName", getHostName());
      jsonObject.put("ipAddresses", StringUtil.merge(getIpAddresses()));
      jsonObject.put("macAddresses", StringUtil.merge(getMacAddresses()));
      jsonObject.put("serverId", Arrays.toString(getServerIdBytes()));
    }

    return jsonObject;
  }

  private static String _decryptResponse(String serverURL, InputStream inputStream)
      throws Exception {

    if (serverURL.startsWith(Http.HTTPS)) {
      return StringUtil.read(inputStream);
    } else {
      byte[] bytes = IOUtils.toByteArray(inputStream);

      if ((bytes == null) || (bytes.length <= 0)) {
        return null;
      }

      bytes = Encryptor.decryptUnencodedAsBytes(_symmetricKey, bytes);

      return new String(bytes, StringPool.UTF8);
    }
  }

  private static byte[] _encryptRequest(String serverURL, String request) throws Exception {

    byte[] bytes = request.getBytes(StringPool.UTF8);

    if (serverURL.startsWith(Http.HTTPS)) {
      return bytes;
    } else {
      JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

      bytes = Encryptor.encryptUnencoded(_symmetricKey, bytes);

      jsonObject.put("content", Base64.objectToString(bytes));
      jsonObject.put("key", _encryptedSymmetricKey);

      return jsonObject.toString().getBytes(StringPool.UTF8);
    }
  }

  private static Map<String, String> _getOrderProducts(JSONObject jsonObject) {

    JSONObject productsJSONObject = jsonObject.getJSONObject("productsJSONObject");

    if (productsJSONObject == null) {
      return null;
    }

    Map<String, String> sortedMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);

    Iterator<String> itr = productsJSONObject.keys();

    while (itr.hasNext()) {
      String key = itr.next();

      sortedMap.put(key, productsJSONObject.getString(key));
    }

    return sortedMap;
  }

  private static void _initKeys() {
    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();

    if ((classLoader == null) || (_encryptedSymmetricKey != null)) {
      return;
    }

    try {
      URL url = classLoader.getResource("com/liferay/portal/license/public.key");

      byte[] bytes = IOUtils.toByteArray(url.openStream());

      X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes);

      KeyFactory keyFactory = KeyFactory.getInstance("RSA");

      PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

      KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

      keyGenerator.init(128, new SecureRandom());

      _symmetricKey = keyGenerator.generateKey();

      byte[] encryptedSymmetricKey =
          Encryptor.encryptUnencoded(publicKey, _symmetricKey.getEncoded());

      _encryptedSymmetricKey = Base64.objectToString(encryptedSymmetricKey);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }

  private static void _registerClusterOrder(
      HttpServletRequest request,
      ClusterNode clusterNode,
      String orderUuid,
      String productEntryName,
      int maxServers)
      throws Exception {

    MethodHandler methodHandler =
        new MethodHandler(_registerOrderMethodKey, orderUuid, productEntryName, maxServers);

    ClusterRequest clusterRequest =
        ClusterRequest.createUnicastRequest(methodHandler, clusterNode.getClusterNodeId());

    FutureClusterResponses futureClusterResponses = ClusterExecutorUtil.execute(clusterRequest);

    ClusterNodeResponses clusterNodeResponses =
        futureClusterResponses.get(20000, TimeUnit.MILLISECONDS);

    ClusterNodeResponse clusterNodeResponse = clusterNodeResponses.getClusterResponse(clusterNode);

    Map<String, Object> attributes = (Map<String, Object>) clusterNodeResponse.getResult();

    for (Map.Entry<String, Object> entry : attributes.entrySet()) {
      request.setAttribute(
          clusterNode.getClusterNodeId() + StringPool.UNDERLINE + entry.getKey(), entry.getValue());
    }
  }

  private static final String _PROXY_PASSWORD =
      GetterUtil.getString(PropsUtil.get("license.proxy.password"));

  private static final int _PROXY_PORT =
      GetterUtil.getInteger(PropsUtil.get("license.proxy.port"), 80);

  private static final String _PROXY_URL = PropsUtil.get("license.proxy.url");

  private static final String _PROXY_USER_NAME =
      GetterUtil.getString(PropsUtil.get("license.proxy.username"));

  private static Log _log = LogFactoryUtil.getLog(DefaultLicenseManagerImpl.class);

  private static String _encryptedSymmetricKey;
  private static MethodHandler _getServerInfoMethodHandler =
      new MethodHandler(new MethodKey(LicenseUtil.class, "getServerInfo"));
  private static String _hostName;
  private static Set<String> _ipAddresses;
  private static Set<String> _macAddresses;
  private static Pattern _macAddressPattern1 =
      Pattern.compile("\\s((\\p{XDigit}{2}(-|:)){5}(\\p{XDigit}{2}))(?:\\s|$)");
  private static Pattern _macAddressPattern2 =
      Pattern.compile("\\s((\\p{XDigit}{1,2}(\\.)){5}(\\p{XDigit}{1,2}))(?:\\s|$)");
  private static MethodKey _registerOrderMethodKey =
      new MethodKey(LicenseUtil.class, "registerOrder", String.class, String.class, int.class);
  private static byte[] _serverIdBytes;
  private static Key _symmetricKey;

  static {
    _initKeys();
  }
}
 protected void addPathElement(StringBuilder sb, String value) {
   sb.append(StringPool.SLASH);
   sb.append(GetterUtil.get(HttpUtil.encodeURL(value), StringPool.DASH));
 }