Ejemplo n.º 1
0
  /**
   * @param xstreamObject not null
   * @param jarFile not null
   * @param packageFilter a package name to filter.
   */
  private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) {
    JarInputStream jarStream = null;
    try {
      jarStream = new JarInputStream(new FileInputStream(jarFile));
      JarEntry jarEntry = jarStream.getNextJarEntry();
      while (jarEntry != null) {
        if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
          String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));
          name = name.replaceAll("/", "\\.");

          if (name.indexOf(packageFilter) != -1) {
            try {
              Class<?> clazz = ClassUtils.getClass(name);
              String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz));
              xstreamObject.alias(alias, clazz);
              if (!clazz.equals(Model.class)) {
                xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field
              }
            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            }
          }
        }

        jarStream.closeEntry();
        jarEntry = jarStream.getNextJarEntry();
      }
    } catch (IOException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("IOException: " + e.getMessage(), e);
      }
    } finally {
      IOUtil.close(jarStream);
    }
  }
Ejemplo n.º 2
0
  public void removeListener(NodeListener listener) {
    if (logger.isDebugEnabled()) {
      logger.debug("## remove listener [{}]", ClassUtils.getShortClassName(listener.getClass()));
    }

    this.listeners.remove(listener);
  }
Ejemplo n.º 3
0
  public void addListener(NodeListener listener) {
    if (logger.isDebugEnabled()) {
      logger.debug(
          "## pipeline[{}] add listener [{}]", ClassUtils.getShortClassName(listener.getClass()));
    }

    this.listeners.add(listener);
  }
Ejemplo n.º 4
0
  public static void main(String[] args) throws Exception {
    initLogName("CreateExportDataBat.log");
    configInit(ClassUtils.getShortClassName(CreateExportDataBat.class));

    CreateExportDataBat bat = new CreateExportDataBat();
    bat.dbInit();
    bat.start();
  }
Ejemplo n.º 5
0
 /**
  * Gets the criteria.
  *
  * @param values the values
  * @param bean the bean
  * @return the criteria
  * @throws ManagerBeanException the manager bean exception
  * @throws ExpressionException the expression exception
  */
 private Criteria getCriteria(IManagerBean bean, Object[] values)
     throws ManagerBeanException, ExpressionException {
   Criteria criteria = null;
   if (values != null) {
     criteria = new Criteria();
     String prefix = ClassUtils.getShortClassName(bean.getPOJOClass()) + "_";
     for (int i = 0; i < values.length; i++) {
       String fieldName = bean.getFieldName(prefix + getForeignJoinProperties().get(i));
       if (values[i] != null) {
         criteria.addExpression(fieldName, values[i].toString());
       } else {
         criteria.addNullExpression(fieldName);
       }
     }
   }
   return criteria;
 }
Ejemplo n.º 6
0
  /**
   * @param expression the user expression.
   * @param obj a not null.
   * @return the XML for the given object.
   */
  private String toXML(String expression, Object obj) {
    XStream currentXStream = getXStream();

    // beautify list
    if (obj instanceof List) {
      List<?> list = (List<?>) obj;
      if (list.size() > 0) {
        Object elt = list.iterator().next();

        String name =
            StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(elt.getClass()));
        currentXStream.alias(pluralize(name), List.class);
      } else {
        // try to detect the alias from question
        if (expression.indexOf(".") != -1) {
          String name = expression.substring(expression.indexOf(".") + 1, expression.indexOf("}"));
          currentXStream.alias(name, List.class);
        }
      }
    }

    return currentXStream.toXML(obj);
  }
Ejemplo n.º 7
0
 /** Just for debug purposes. {@inheritDoc} */
 @Override
 public String toString() {
   return ClassUtils.getShortClassName(getClass()) + "[<" + getTagName() + " ...>]";
 }
Ejemplo n.º 8
0
 private static String getShortClassname(Class clazz) {
   return ClassUtils.getShortClassName(clazz);
 }
Ejemplo n.º 9
0
  // ======================== help method ===================
  // 保存对应的dbBatch
  private HttpPipeKey saveDbBatch(DbBatch dbBatch) {
    RowBatch rowBatch = dbBatch.getRowBatch();
    // 转化为proto对象
    BatchProto.RowBatch.Builder rowBatchBuilder = BatchProto.RowBatch.newBuilder();
    rowBatchBuilder.setIdentity(build(rowBatch.getIdentity()));
    // 处理具体的字段rowData
    for (EventData eventData : rowBatch.getDatas()) {
      BatchProto.RowData.Builder rowDataBuilder = BatchProto.RowData.newBuilder();
      rowDataBuilder.setPairId(eventData.getPairId());
      rowDataBuilder.setTableId(eventData.getTableId());
      if (eventData.getSchemaName() != null) {
        rowDataBuilder.setSchemaName(eventData.getSchemaName());
      }
      rowDataBuilder.setTableName(eventData.getTableName());
      rowDataBuilder.setEventType(eventData.getEventType().getValue());
      rowDataBuilder.setExecuteTime(eventData.getExecuteTime());
      // add by ljh at 2012-10-31
      if (eventData.getSyncMode() != null) {
        rowDataBuilder.setSyncMode(eventData.getSyncMode().getValue());
      }
      if (eventData.getSyncConsistency() != null) {
        rowDataBuilder.setSyncConsistency(eventData.getSyncConsistency().getValue());
      }

      // 构造key column
      for (EventColumn keyColumn : eventData.getKeys()) {
        rowDataBuilder.addKeys(buildColumn(keyColumn));
      }
      // 构造old key column
      if (CollectionUtils.isEmpty(eventData.getOldKeys()) == false) {
        for (EventColumn keyColumn : eventData.getOldKeys()) {
          rowDataBuilder.addOldKeys(buildColumn(keyColumn));
        }
      }

      // 构造其他 column
      for (EventColumn column : eventData.getColumns()) {
        rowDataBuilder.addColumns(buildColumn(column));
      }

      rowDataBuilder.setRemedy(eventData.isRemedy());
      rowDataBuilder.setSize(eventData.getSize());
      rowBatchBuilder.addRows(rowDataBuilder.build()); // 添加一条rowData记录
    }

    // 处理下FileBatch
    FileBatch fileBatch = dbBatch.getFileBatch();
    BatchProto.FileBatch.Builder fileBatchBuilder = null;
    fileBatchBuilder = BatchProto.FileBatch.newBuilder();
    fileBatchBuilder.setIdentity(build(fileBatch.getIdentity()));
    // 构造对应的proto对象
    for (FileData fileData : fileBatch.getFiles()) {
      BatchProto.FileData.Builder fileDataBuilder = BatchProto.FileData.newBuilder();
      fileDataBuilder.setPairId(fileData.getPairId());
      fileDataBuilder.setTableId(fileData.getTableId());
      if (fileData.getNameSpace() != null) {
        fileDataBuilder.setNamespace(fileData.getNameSpace());
      }
      if (fileData.getPath() != null) {
        fileDataBuilder.setPath(fileData.getPath());
      }
      fileDataBuilder.setEventType(fileData.getEventType().getValue());
      fileDataBuilder.setSize(fileData.getSize());
      fileDataBuilder.setLastModifiedTime(fileData.getLastModifiedTime());

      fileBatchBuilder.addFiles(fileDataBuilder.build()); // 添加一条fileData记录
    }
    // 处理构造对应的文件url
    String filename =
        buildFileName(rowBatch.getIdentity(), ClassUtils.getShortClassName(dbBatch.getClass()));
    // 写入数据
    File file = new File(htdocsDir, filename);
    OutputStream output = null;
    try {
      output = new BufferedOutputStream(new FileOutputStream(file));
      com.alibaba.otter.node.etl.model.protobuf.BatchProto.RowBatch rowBatchProto =
          rowBatchBuilder.build();
      output.write(ByteUtils.int2bytes(rowBatchProto.getSerializedSize())); // 输出大小
      rowBatchProto.writeTo(output); // 输出row batch

      com.alibaba.otter.node.etl.model.protobuf.BatchProto.FileBatch fileBatchProto =
          fileBatchBuilder.build();
      output.write(ByteUtils.int2bytes(fileBatchProto.getSerializedSize())); // 输出大小
      fileBatchProto.writeTo(output); // 输出file batch
      output.flush();
    } catch (IOException e) {
      throw new PipeException("write_byte_error", e);
    } finally {
      IOUtils.closeQuietly(output);
    }

    HttpPipeKey key = new HttpPipeKey();
    key.setUrl(remoteUrlBuilder.getUrl(rowBatch.getIdentity().getPipelineId(), filename));
    key.setDataType(PipeDataType.DB_BATCH);
    key.setIdentity(rowBatch.getIdentity());
    Pipeline pipeline = configClientService.findPipeline(rowBatch.getIdentity().getPipelineId());
    if (pipeline.getParameters().getUseFileEncrypt()) {
      // 加密处理
      EncryptedData encryptedData = encryptFile(file);
      key.setKey(encryptedData.getKey());
      key.setCrc(encryptedData.getCrc());
    }

    return key;
  }
Ejemplo n.º 10
0
  /**
   * http form multipart form post
   *
   * @param connection
   * @param activationContent
   * @throws ExchangeException
   */
  public static void transport(URLConnection connection, ActivationContent activationContent)
      throws ExchangeException {
    FileInputStream fis = null;
    DataOutputStream outStream = null;
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setUseCaches(false);
      connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
      connection.setRequestProperty("Cache-Control", "no-cache");

      outStream = new DataOutputStream(connection.getOutputStream());
      outStream.writeBytes("--" + BOUNDARY + "\r\n");

      // set all resources from activationContent
      Iterator fileNameIterator = activationContent.getFiles().keySet().iterator();
      while (fileNameIterator.hasNext()) {
        String fileName = (String) fileNameIterator.next();
        fis = new FileInputStream(activationContent.getFile(fileName));
        outStream.writeBytes(
            "content-disposition: form-data; name=\""
                + fileName
                + "\"; filename=\""
                + fileName
                + "\"\r\n");
        outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
        while (true) {
          synchronized (buffer) {
            int amountRead = fis.read(buffer);
            if (amountRead == -1) {
              break;
            }
            outStream.write(buffer, 0, amountRead);
          }
        }
        fis.close();
        outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n");
      }
      outStream.flush();
      outStream.close();

      log.debug("Activation content sent as multipart/form-data");
    } catch (Exception e) {
      throw new ExchangeException(
          "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          log.error("Exception caught", e);
        }
      }
      if (outStream != null) {
        try {
          outStream.close();
        } catch (IOException e) {
          log.error("Exception caught", e);
        }
      }
    }
  }
Ejemplo n.º 11
0
  /**
   * gets the annotation but also adds an import in the process if a Convert annotation is required.
   */
  @Override
  protected NodeData getAnnotationNodes(
      String enclosingClass, String fieldName, String mappedClass) {
    final ObjectReferenceDescriptor ord =
        OjbUtil.findObjectReferenceDescriptor(mappedClass, fieldName, descriptorRepositories);
    if (ord != null) {
      final List<MemberValuePair> pairs = new ArrayList<MemberValuePair>();
      final Collection<ImportDeclaration> additionalImports = new ArrayList<ImportDeclaration>();

      final Collection<String> fks = ord.getForeignKeyFields();
      if (fks == null || fks.isEmpty()) {
        LOG.error(
            ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                + " field has a reference descriptor for "
                + fieldName
                + " but does not have any foreign keys configured");
        return null;
      }

      final Collection<String> pks =
          OjbUtil.getPrimaryKeyNames(mappedClass, descriptorRepositories);

      if (!(pks.size() == fks.size() && pks.containsAll(fks))) {
        final String className = ord.getItemClassName();
        if (StringUtils.isBlank(className)) {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has a reference descriptor for "
                  + fieldName
                  + " but does not class name attribute");
        } else {
          final String shortClassName = ClassUtils.getShortClassName(className);
          final String packageName = ClassUtils.getPackageName(className);
          pairs.add(new MemberValuePair("targetEntity", new NameExpr(shortClassName + ".class")));
          additionalImports.add(
              new ImportDeclaration(
                  new QualifiedNameExpr(new NameExpr(packageName), shortClassName), false, false));
        }

        final boolean proxy = ord.isLazy();
        if (proxy) {
          pairs.add(new MemberValuePair("fetch", new NameExpr("FetchType.LAZY")));
          additionalImports.add(
              new ImportDeclaration(
                  new QualifiedNameExpr(new NameExpr(PACKAGE), "FetchType"), false, false));
        }

        final boolean refresh = ord.isRefresh();
        if (refresh) {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has refresh set to "
                  + refresh
                  + ", unsupported conversion to @OneToOne attributes");
        }

        final List<Expression> cascadeTypes = new ArrayList<Expression>();
        final boolean autoRetrieve = ord.getCascadeRetrieve();
        if (autoRetrieve) {
          cascadeTypes.add(new NameExpr("CascadeType.REFRESH"));
        } else {
          // updated default logging - false would result no additional annotations
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                    + " field has auto-retrieve set to "
                    + autoRetrieve
                    + ", unsupported conversion to CascadeType");
          }
        }

        final int autoDelete = ord.getCascadingDelete();
        if (autoDelete == ObjectReferenceDescriptor.CASCADE_NONE) {
          // updated default logging - none would result no additional annotations
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                    + " field has auto-delete set to none, unsupported conversion to CascadeType");
          }
        } else if (autoDelete == ObjectReferenceDescriptor.CASCADE_LINK) {
          LOG.warn(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-delete set to link, unsupported conversion to CascadeType");
        } else if (autoDelete == ObjectReferenceDescriptor.CASCADE_OBJECT) {
          cascadeTypes.add(new NameExpr("CascadeType.REMOVE"));
        } else {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-delete set to an invalid value");
        }

        final int autoUpdate = ord.getCascadingStore();
        if (autoUpdate == ObjectReferenceDescriptor.CASCADE_NONE) {
          // updated default logging - none would result no additional annotations
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                    + " field has auto-update set to none, unsupported conversion to CascadeType");
          }
        } else if (autoUpdate == ObjectReferenceDescriptor.CASCADE_LINK) {
          LOG.warn(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-update set to link, unsupported conversion to CascadeType");
        } else if (autoUpdate == ObjectReferenceDescriptor.CASCADE_OBJECT) {
          cascadeTypes.add(new NameExpr("CascadeType.PERSIST"));
        } else {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-update set to an invalid value");
        }

        if (!cascadeTypes.isEmpty()) {
          pairs.add(new MemberValuePair("cascade", new ArrayInitializerExpr(cascadeTypes)));
          additionalImports.add(
              new ImportDeclaration(
                  new QualifiedNameExpr(new NameExpr(PACKAGE), "CascadeType"), false, false));
        }

        return new NodeData(
            new NormalAnnotationExpr(new NameExpr(SIMPLE_NAME), pairs),
            new ImportDeclaration(
                new QualifiedNameExpr(new NameExpr(PACKAGE), SIMPLE_NAME), false, false),
            additionalImports);
      }
    }
    return null;
  }
Ejemplo n.º 12
0
  public static void copyModeltoModel(Object src, Object des) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(des); // 得到to对象的字段属性集合
    for (int i = 0; i < pds.length; i++) {
      try {
        // 得到to对象的属性的类型
        String toClassName = ClassUtils.getShortClassName(pds[i].getPropertyType());
        // 根据此字段名去from对象查找 如果找不到则跳过 继续下一个to字段的赋值
        PropertyDescriptor descriptor = null;
        try {
          descriptor = PropertyUtils.getPropertyDescriptor(src, pds[i].getDisplayName());
          if (descriptor == null) {
            continue; // Skip this property setter
          }
        } catch (NoSuchMethodException e) {
          continue; // Skip this property setter
        }
        // 得到form对象该字段的类型
        String fromClassName = ClassUtils.getShortClassName(descriptor.getPropertyType());

        if ("Class".equals(toClassName)) {
          continue;
        } else {
          // 得到form字段该字段的值 如果有值则赋值 否则继续下一个
          // System.out.println("\n\n\n pds[i].getDisplayName()=" +
          // pds[i].getDisplayName() + "\n\n\n");
          Object o = PropertyUtils.getProperty(src, pds[i].getDisplayName());
          if (o != null) {
            if (toClassName.equals("Date") && fromClassName.equals("String")) { // 如果form该字段是字符串
              // o = Helper.switchDate((String) o);
              // BeanUtils.setProperty(des,
              // pds[i].getDisplayName(), o);
              ConvertUtilsBean convertUtils = new ConvertUtilsBean();
              convertUtils.register(new DateConverter(), Date.class);
              BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils, new PropertyUtilsBean());
              o = Helper.switchDate((String) o);
              beanUtils.setProperty(des, pds[i].getDisplayName(), o);
            } else if (toClassName.equals("String") && fromClassName.equals("Date")) {
              o = DateUtil.toStringByFormat((Date) o, "yyyy-MM-dd HH:mm:ss");
              if (org.apache.commons.lang.StringUtils.contains((String) o, "00:00:00")) {
                o =
                    org.apache.commons.lang.StringUtils.substringBeforeLast((String) o, "00:00:00")
                        .trim();
              }
              org.apache.commons.beanutils.BeanUtils.setProperty(des, pds[i].getDisplayName(), o);
            } else if (toClassName.equals("Date") && fromClassName.equals("Date")) {
              ConvertUtilsBean convertUtils = new ConvertUtilsBean();
              convertUtils.register(new DateConverter(), Date.class);
              BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils, new PropertyUtilsBean());
              beanUtils.setProperty(des, pds[i].getDisplayName(), o);
              // BeanUtils.setProperty(des,
              // pds[i].getDisplayName(), o);
            } else {
              org.apache.commons.beanutils.BeanUtils.setProperty(des, pds[i].getDisplayName(), o);
            }
            // org.apache.commons.beanutils.BeanUtils.setProperty(des,pds[i].getDisplayName(),o);
          }
        }
      } catch (Exception ex) {
        // System.out.println("赋值失败:" + ex);
      }
    }
  }
  public JSONObject describeOperator(String clazz) throws Exception {
    TypeGraphVertex tgv = typeGraph.getTypeGraphVertex(clazz);
    if (tgv.isInstantiable()) {
      JSONObject response = new JSONObject();
      JSONArray inputPorts = new JSONArray();
      JSONArray outputPorts = new JSONArray();
      // Get properties from ASM

      JSONObject operatorDescriptor = describeClassByASM(clazz);
      JSONArray properties = operatorDescriptor.getJSONArray("properties");

      properties = enrichProperties(clazz, properties);

      JSONArray portTypeInfo = operatorDescriptor.getJSONArray("portTypeInfo");

      List<CompactFieldNode> inputPortfields = typeGraph.getAllInputPorts(clazz);
      List<CompactFieldNode> outputPortfields = typeGraph.getAllOutputPorts(clazz);

      try {
        for (CompactFieldNode field : inputPortfields) {
          JSONObject inputPort = setFieldAttributes(clazz, field);
          if (!inputPort.has("optional")) {
            inputPort.put(
                "optional",
                false); // input port that is not annotated is default to be not optional
          }
          if (!inputPort.has(SCHEMA_REQUIRED_KEY)) {
            inputPort.put(SCHEMA_REQUIRED_KEY, false);
          }
          inputPorts.put(inputPort);
        }

        for (CompactFieldNode field : outputPortfields) {
          JSONObject outputPort = setFieldAttributes(clazz, field);

          if (!outputPort.has("optional")) {
            outputPort.put(
                "optional", true); // output port that is not annotated is default to be optional
          }
          if (!outputPort.has("error")) {
            outputPort.put("error", false);
          }
          if (!outputPort.has(SCHEMA_REQUIRED_KEY)) {
            outputPort.put(SCHEMA_REQUIRED_KEY, false);
          }
          outputPorts.put(outputPort);
        }

        response.put("name", clazz);
        response.put("properties", properties);
        response.put(PORT_TYPE_INFO_KEY, portTypeInfo);
        response.put("inputPorts", inputPorts);
        response.put("outputPorts", outputPorts);

        OperatorClassInfo oci = classInfo.get(clazz);

        if (oci != null) {
          if (oci.comment != null) {
            String[] descriptions;
            // first look for a <p> tag
            String keptPrefix = "<p>";
            descriptions = oci.comment.split("<p>", 2);
            if (descriptions.length == 0) {
              keptPrefix = "";
              // if no <p> tag, then look for a blank line
              descriptions = oci.comment.split("\n\n", 2);
            }
            if (descriptions.length > 0) {
              response.put("shortDesc", descriptions[0]);
            }
            if (descriptions.length > 1) {
              response.put("longDesc", keptPrefix + descriptions[1]);
            }
          }
          response.put("category", oci.tags.get("@category"));
          String displayName = oci.tags.get("@displayName");
          if (displayName == null) {
            displayName = decamelizeClassName(ClassUtils.getShortClassName(clazz));
          }
          response.put("displayName", displayName);
          String tags = oci.tags.get("@tags");
          if (tags != null) {
            JSONArray tagArray = new JSONArray();
            for (String tag : StringUtils.split(tags, ',')) {
              tagArray.put(tag.trim().toLowerCase());
            }
            response.put("tags", tagArray);
          }
          String doclink = oci.tags.get("@doclink");
          if (doclink != null) {
            response.put("doclink", doclink + "?" + getDocName(clazz));
          } else if (clazz.startsWith("com.datatorrent.lib.")
              || clazz.startsWith("com.datatorrent.contrib.")) {
            response.put("doclink", DT_OPERATOR_DOCLINK_PREFIX + "?" + getDocName(clazz));
          }
        }
      } catch (JSONException ex) {
        throw new RuntimeException(ex);
      }
      return response;
    } else {
      throw new UnsupportedOperationException();
    }
  }
 /* (non-Javadoc)
  * @see org.codehaus.groovy.grails.commons.GrailsDomainClassProperty#getTypePropertyName()
  */
 public String getTypePropertyName() {
   String shortTypeName = ClassUtils.getShortClassName(this.type);
   return shortTypeName.substring(0, 1).toLowerCase(Locale.ENGLISH) + shortTypeName.substring(1);
 }
 private String getClassname4History(final Class<?> cls) {
   return ClassUtils.getShortClassName(cls);
 }
/**
 * The Class <code>
 * com.bitdubai.fermat_p2p_plugin.layer.ws.communications.cloud.server.developer.bitdubai.version_1.WsCommunicationsServerCloudPluginRoot
 * </code> is the responsible to initialize all component to work together, and hold all resources
 * they needed.
 *
 * <p>Created by Roberto Requena - ([email protected]) on 03/09/15.
 *
 * @version 1.0
 */
public class WsCommunicationsServerCloudPluginRoot
    implements Service,
        DealsWithEvents,
        DealsWithLogger,
        LogManagerForDevelopers,
        DealsWithErrors,
        DealsWithPluginFileSystem,
        Plugin {

  /** Represent the logger instance */
  private Logger LOG =
      Logger.getLogger(ClassUtils.getShortClassName(WsCommunicationsServerCloudPluginRoot.class));

  /** Represents the value of DISABLE_SERVER */
  public static final Boolean DISABLE_SERVER = Boolean.TRUE;

  /** Represents the value of ENABLE_SERVER */
  public static final Boolean ENABLE_SERVER = Boolean.FALSE;

  /** Represent the status of this service */
  private ServiceStatus serviceStatus = ServiceStatus.CREATED;

  /** Represent the errorManager */
  private ErrorManager errorManager;

  /** Represent the eventManager */
  private EventManager eventManager;

  /** Represent the logManager */
  private LogManager logManager;

  /** Represent the newLoggingLevel */
  static Map<String, LogLevel> newLoggingLevel = new HashMap<String, LogLevel>();

  /** Hold the list of event listeners */
  private List<FermatEventListener> listenersAdded = new ArrayList<>();

  /** Represent the wsCommunicationCloudServer */
  private WsCommunicationCloudServer wsCommunicationCloudServer;

  /** DealsWithPluginIdentity Interface member variables. */
  private UUID pluginId;

  /** Represent the disableServerFlag */
  private Boolean disableServerFlag;

  /** Represent the wsCommunicationsCloudServerPingAgent */
  private WsCommunicationsCloudServerPingAgent wsCommunicationsCloudServerPingAgent;

  /** Constructor */
  public WsCommunicationsServerCloudPluginRoot() {
    super();
    this.disableServerFlag = WsCommunicationsServerCloudPluginRoot.DISABLE_SERVER;
  }

  /**
   * This method validate is all required resource are injected into the plugin root by the platform
   *
   * @throws CantStartPluginException
   */
  private void validateInjectedResources() throws CantStartPluginException {

    /*
     * If all resources are inject
     */
    if (eventManager == null || logManager == null || errorManager == null) {

      StringBuffer contextBuffer = new StringBuffer();
      contextBuffer.append("Plugin ID: " + pluginId);
      contextBuffer.append(CantStartPluginException.CONTEXT_CONTENT_SEPARATOR);
      contextBuffer.append("eventManager: " + eventManager);
      contextBuffer.append(CantStartPluginException.CONTEXT_CONTENT_SEPARATOR);
      contextBuffer.append("logManager: " + logManager);
      contextBuffer.append(CantStartPluginException.CONTEXT_CONTENT_SEPARATOR);
      contextBuffer.append("errorManager: " + errorManager);

      LOG.error("No all required resource are injected");
      LOG.error("contextBuffer = " + contextBuffer);

      String context = contextBuffer.toString();
      String possibleCause = "No all required resource are injected";
      CantStartPluginException pluginStartException =
          new CantStartPluginException(
              CantStartPluginException.DEFAULT_MESSAGE, null, context, possibleCause);

      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_WS_COMMUNICATION_CLIENT_CHANNEL,
          UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN,
          pluginStartException);
      throw pluginStartException;
    }
  }

  @Override
  public FermatManager getManager() {
    return null;
  }

  /**
   * (non-Javadoc)
   *
   * @see Service#start()
   */
  @Override
  public void start() {

    try {

      /*
       * Validate required resources
       */
      // validateInjectedResources();

      if (disableServerFlag) {
        LOG.info("Local Server is Disable, no started");
        return;
      }

      LOG.info("Starting plugin");

      JettyEmbeddedAppServer.getInstance().start();

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }

    /*
     * Set the new status of the service
     */
    this.serviceStatus = ServiceStatus.STARTED;
  }

  /**
   * (non-Javadoc)
   *
   * @see Service#pause()
   */
  @Override
  public void pause() {
    this.serviceStatus = ServiceStatus.PAUSED;
  }

  /**
   * (non-Javadoc)
   *
   * @see Service#resume()
   */
  @Override
  public void resume() {
    this.serviceStatus = ServiceStatus.STARTED;
  }

  /**
   * (non-Javadoc)
   *
   * @see Service#stop()
   */
  @Override
  public void stop() {

    /*
     * Remove all the event listeners registered with the event manager.
     */
    for (FermatEventListener fermatEventListener : listenersAdded) {
      eventManager.removeListener(fermatEventListener);
    }

    /*
     * Clear the list
     */
    listenersAdded.clear();

    /*
     * Change the estatus
     */
    this.serviceStatus = ServiceStatus.STOPPED;
  }

  /**
   * (non-Javadoc)
   *
   * @see Service#getStatus()
   */
  @Override
  public ServiceStatus getStatus() {
    return this.serviceStatus;
  }

  /**
   * (non-Javadoc)
   *
   * @see DealsWithLogger#setLogManager(LogManager)
   */
  @Override
  public void setLogManager(LogManager logManager) {
    this.logManager = logManager;
  }

  /**
   * (non-Javadoc)
   *
   * @see LogManagerForDevelopers#getClassesFullPath()
   */
  @Override
  public List<String> getClassesFullPath() {
    List<String> returnedClasses = new ArrayList<String>();
    returnedClasses.add(
        "com.bitdubai.fermat_p2p_plugin.layer.communication.cloud_server.developer.bitdubai.version_1.WsCommunicationsServerCloudPluginRoot");
    returnedClasses.add(
        "com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.ECCKeyPair");
    /** I return the values. */
    return returnedClasses;
  }

  /**
   * (non-Javadoc)
   *
   * @see LogManagerForDevelopers#setLoggingLevelPerClass(Map<String, LogLevel>)
   */
  @Override
  public void setLoggingLevelPerClass(Map<String, LogLevel> newLoggingLevel) {
    /** I will check the current values and update the LogLevel in those which is different */
    for (Map.Entry<String, LogLevel> pluginPair : newLoggingLevel.entrySet()) {
      /**
       * if this path already exists in the Root.bewLoggingLevel I'll update the value, else, I will
       * put as new
       */
      if (WsCommunicationsServerCloudPluginRoot.newLoggingLevel.containsKey(pluginPair.getKey())) {
        WsCommunicationsServerCloudPluginRoot.newLoggingLevel.remove(pluginPair.getKey());
        WsCommunicationsServerCloudPluginRoot.newLoggingLevel.put(
            pluginPair.getKey(), pluginPair.getValue());
      } else {
        WsCommunicationsServerCloudPluginRoot.newLoggingLevel.put(
            pluginPair.getKey(), pluginPair.getValue());
      }
    }
  }

  /**
   * Static method to get the logging level from any class under root.
   *
   * @param className
   * @return
   */
  public static LogLevel getLogLevelByClass(String className) {
    try {
      /**
       * sometimes the classname may be passed dinamically with an $moretext I need to ignore whats
       * after this.
       */
      String[] correctedClass = className.split((Pattern.quote("$")));
      return WsCommunicationsServerCloudPluginRoot.newLoggingLevel.get(correctedClass[0]);
    } catch (Exception e) {
      /** If I couldn't get the correct loggin level, then I will set it to minimal. */
      return DEFAULT_LOG_LEVEL;
    }
  }

  /**
   * (non-Javadoc)
   *
   * @see DealsWithPluginFileSystem#setPluginFileSystem(PluginFileSystem)
   */
  @Override
  public void setPluginFileSystem(PluginFileSystem pluginFileSystem) {
    // this.pluginFileSystem = pluginFileSystem;
  }

  /**
   * (non-Javadoc)
   *
   * @see DealsWithEvents#setEventManager(EventManager)
   */
  @Override
  public void setEventManager(EventManager eventManager) {
    this.eventManager = eventManager;
  }

  /**
   * (non-Javadoc)
   *
   * @see DealsWithErrors#setErrorManager(ErrorManager)
   */
  @Override
  public void setErrorManager(ErrorManager errorManager) {
    this.errorManager = errorManager;
  }

  /**
   * (non-Javadoc)
   *
   * @see Plugin#setId(UUID)
   */
  @Override
  public void setId(UUID pluginId) {
    this.pluginId = pluginId;
  }

  /**
   * Get the disable server flag
   *
   * @return Boolean
   */
  public Boolean getDisableServerFlag() {
    return disableServerFlag;
  }

  /**
   * Set Disable Server Flag
   *
   * @param disableServerFlag
   */
  public void setDisableServerFlag(Boolean disableServerFlag) {
    this.disableServerFlag = disableServerFlag;
  }
}