/**
  * @deprecated As of build 4512, replaced by {@link #getInstance() and #getString(String, String,
  *     String, String, String, String)}
  */
 @Deprecated
 public static String getSystemString(
     String key, String param1, String param2, String param3, String param4, String param5) {
   try {
     return GlobalMessageUtil.getString(
         getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)),
         key,
         param1,
         param2,
         param3,
         param4,
         param5);
   } catch (MissingResourceException e) {
     try {
       return GlobalMessageUtil.getString(
           getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)),
           key,
           param1,
           param2,
           param3,
           param4,
           param5);
     } catch (MissingResourceException fe) {
       LogWriter.getInstance()
           .logError("Internationalisation/Translation error", Const.getStackTracker(e));
       return '!' + key + '!';
     }
   }
 }
 protected String findString(String packageName, Locale locale, String key, Object[] parameters)
     throws MissingResourceException {
   try {
     ResourceBundle bundle = getBundle(locale, packageName + "." + BUNDLE_NAME);
     String unformattedString = bundle.getString(key);
     String string = MessageFormat.format(unformattedString, parameters);
     return string;
   } catch (IllegalArgumentException e) {
     String message =
         "Format problem with key=["
             + key
             + "], locale=["
             + locale
             + "], package="
             + packageName
             + " : "
             + e.toString();
     LogWriter.getInstance().logError("i18n", message);
     LogWriter.getInstance().logError("i18n", Const.getStackTracker(e));
     throw new MissingResourceException(message, packageName, key);
   }
 }
  public RowMetaInterface getTableFields() {
    LogWriter log = LogWriter.getInstance();
    RowMetaInterface fields = null;
    if (databaseMeta != null) {
      Database db = new Database(databaseMeta);
      databases = new Database[] {db}; // Keep track of this one for cancelQuery

      try {
        db.connect();
        String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tablename);
        fields = db.getTableFields(schemaTable);
      } catch (KettleDatabaseException dbe) {
        log.logError(
            toString(),
            Messages.getString("DatabaseLookupMeta.ERROR0004.ErrorGettingTableFields")
                + dbe.getMessage()); // $NON-NLS-1$
      } finally {
        db.disconnect();
      }
    }
    return fields;
  }
  protected String calculateString(String packageName, String key, Object[] parameters) {
    String string = null;

    // First try the standard locale, in the local package
    try {
      string = findString(packageName, langChoice.getDefaultLocale(), key, parameters);
    } catch (MissingResourceException e) {
    }
    ;
    if (string != null) return string;

    // Then try to find it in the i18n package, in the system messages of the preferred language.
    try {
      string = findString(SYSTEM_BUNDLE_PACKAGE, langChoice.getDefaultLocale(), key, parameters);
    } catch (MissingResourceException e) {
    }
    ;
    if (string != null) return string;

    // Then try the failover locale, in the local package
    try {
      string = findString(packageName, langChoice.getFailoverLocale(), key, parameters);
    } catch (MissingResourceException e) {
    }
    ;
    if (string != null) return string;

    // Then try to find it in the i18n package, in the system messages of the failover language.
    try {
      string = findString(SYSTEM_BUNDLE_PACKAGE, langChoice.getFailoverLocale(), key, parameters);
    } catch (MissingResourceException e) {
    }
    ;
    if (string != null) return string;

    string = "!" + key + "!";
    String message =
        "Message not found in the preferred and failover locale: key=["
            + key
            + "], package="
            + packageName;
    LogWriter.getInstance()
        .logDetailed("i18n", Const.getStackTracker(new KettleException(message)));

    return string;
  }
  /** @deprecated As of build 4512, replaced by {@link #getInstance() and #getString(String)} */
  @Deprecated
  public static String getSystemString(String key) {
    try {
      return GlobalMessageUtil.getString(
          getBundle(langChoice.getDefaultLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key);
    } catch (MissingResourceException e) {
      try {
        return GlobalMessageUtil.getString(
            getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key);
      } catch (MissingResourceException fe) {
        LogWriter.getInstance()
            .logError("Internationalisation/Translation error", Const.getStackTracker(e));
        return '!' + key + '!';
      }
    }

    /*
    try
    {
        ResourceBundle bundle = getBundle(langChoice.getDefaultLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE));
        return bundle.getString(key);
    }
    catch (MissingResourceException e)
    {
        // OK, try to find the key in the alternate failover locale
        try
        {
            ResourceBundle bundle = getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE));
            return bundle.getString(key);
        }
        catch (MissingResourceException fe)
        {
            LogWriter.getInstance().logError("Internationalisation/Translation error", Const.getStackTracker(e));
            return '!' + key + '!';
        }
    }
    */
  }
  public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);

    if (filename != null) {
      String realFilename = getRealFilename();
      try {
        FileObject file = KettleVFS.getFileObject(realFilename);
        if (file.exists() && file.isReadable()) {
          log.logDetailed(
              toString(),
              Messages.getString("JobEntryFileExists.File_Exists", realFilename)); // $NON-NLS-1$
          result.setResult(true);
        } else {
          log.logDetailed(
              toString(),
              Messages.getString(
                  "JobEntryFileExists.File_Does_Not_Exist", realFilename)); // $NON-NLS-1$
        }
      } catch (IOException e) {
        result.setNrErrors(1);
        log.logError(
            toString(),
            Messages.getString(
                "JobEntryFileExists.ERROR_0004_IO_Exception", e.toString())); // $NON-NLS-1$
      }
    } else {
      result.setNrErrors(1);
      log.logError(
          toString(),
          Messages.getString("JobEntryFileExists.ERROR_0005_No_Filename_Defined")); // $NON-NLS-1$
    }

    return result;
  }
  public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    log4j.info(Messages.getString("JobEntrySNMPTrap.Started", serverName)); // $NON-NLS-1$

    Result result = previousResult;
    result.setNrErrors(1);
    result.setResult(false);

    String servername = environmentSubstitute(serverName);
    int nrPort = Const.toInt(environmentSubstitute("" + port), DEFAULT_PORT);
    String Oid = environmentSubstitute(oid);
    int timeOut = Const.toInt(environmentSubstitute("" + timeout), DEFAULT_TIME_OUT);
    int retry = Const.toInt(environmentSubstitute("" + nrretry), 1);
    String messageString = environmentSubstitute(message);

    Snmp snmp = null;

    try {
      TransportMapping transMap = new DefaultUdpTransportMapping();
      snmp = new Snmp(transMap);

      UdpAddress udpAddress = new UdpAddress(InetAddress.getByName(servername), nrPort);
      ResponseEvent response = null;
      if (targettype.equals(target_type_Code[0])) {
        // Community target
        String community = environmentSubstitute(comString);

        CommunityTarget target = new CommunityTarget();
        PDUv1 pdu1 = new PDUv1();
        transMap.listen();

        target.setCommunity(new OctetString(community));
        target.setVersion(SnmpConstants.version1);
        target.setAddress(udpAddress);
        if (target.getAddress().isValid()) {
          if (log.isDebug()) log.logDebug(toString(), "Valid IP address");
        } else throw new KettleException("Invalid IP address");
        target.setRetries(retry);
        target.setTimeout(timeOut);

        // create the PDU
        pdu1.setGenericTrap(6);
        pdu1.setSpecificTrap(PDUv1.ENTERPRISE_SPECIFIC);
        pdu1.setEnterprise(new OID(Oid));
        pdu1.add(new VariableBinding(new OID(Oid), new OctetString(messageString)));

        response = snmp.send(pdu1, target);

      } else {
        // User target
        String userName = environmentSubstitute(user);
        String passPhrase = environmentSubstitute(passphrase);
        String engineID = environmentSubstitute(engineid);

        UserTarget usertarget = new UserTarget();
        transMap.listen();
        usertarget.setAddress(udpAddress);
        if (usertarget.getAddress().isValid()) {
          if (log.isDebug()) log.logDebug(toString(), "Valid IP address");
        } else throw new KettleException("Invalid IP address");

        usertarget.setRetries(retry);
        usertarget.setTimeout(timeOut);
        usertarget.setVersion(SnmpConstants.version3);
        usertarget.setSecurityLevel(SecurityLevel.AUTH_PRIV);
        usertarget.setSecurityName(new OctetString("MD5DES"));

        // Since we are using SNMPv3 we use authenticated users
        // this is handled by the UsmUser and USM class

        UsmUser uu =
            new UsmUser(
                new OctetString(userName),
                AuthMD5.ID,
                new OctetString(passPhrase),
                PrivDES.ID,
                new OctetString(passPhrase));

        if (uu == null) {
          throw new KettleException("Null UsmUser");
        } else {
          if (log.isDebug()) log.logDebug(toString(), "Valid UsmUser");
        }

        USM usm = snmp.getUSM();

        if (usm == null) throw new KettleException("Null Usm");
        else {
          usm =
              new USM(
                  SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
          usm.addUser(new OctetString(userName), uu);
          if (log.isDebug()) log.logDebug(toString(), "Valid Usm");
        }

        // create the PDU
        ScopedPDU pdu = new ScopedPDU();
        pdu.add(new VariableBinding(new OID(Oid), new OctetString(messageString)));
        pdu.setType(PDU.TRAP);
        if (!Const.isEmpty(engineID)) pdu.setContextEngineID(new OctetString(engineID));

        // send the PDU
        response = snmp.send(pdu, usertarget);
      }

      if (response == null) {

      } else {
        if (log.isDebug())
          log.logDebug(
              toString(),
              "Received response from: " + response.getPeerAddress() + response.toString());
      }

      result.setNrErrors(0);
      result.setResult(true);
    } catch (Exception e) {
      log.logError(
          toString(),
          Messages.getString("JobEntrySNMPTrap.ErrorGetting", e.getMessage())); // $NON-NLS-1$
    } finally {
      try {
        if (snmp != null) snmp.close();
      } catch (Exception e) {
      }
      ;
    }

    return result;
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!request.getRequestURI().equals(CONTEXT_PATH + "/")) return;

    if (log.isDebug()) log.logDebug(toString(), "Slave Server registration requested");

    PrintWriter out = response.getWriter();
    BufferedReader in = request.getReader();
    if (log.isDetailed())
      log.logDetailed(toString(), "Encoding: " + request.getCharacterEncoding());

    // We always use XML to reply here...
    //
    response.setContentType("text/xml");
    out.print(XMLHandler.getXMLHeader());
    response.setStatus(HttpServletResponse.SC_OK);

    try {
      // First read the slave server information in memory from the request
      //
      StringBuilder xml = new StringBuilder(request.getContentLength());
      int c;
      while ((c = in.read()) != -1) {
        xml.append((char) c);
      }

      // Parse the XML, create a transformation configuration
      //
      Document document = XMLHandler.loadXMLString(xml.toString());
      Node node = XMLHandler.getSubNode(document, SlaveServerDetection.XML_TAG);
      SlaveServerDetection slaveServerDetection = new SlaveServerDetection(node);

      // See if this slave server is already in our list...
      //
      String message;
      int index = detections.indexOf(slaveServerDetection);
      if (index < 0) {
        detections.add(slaveServerDetection);
        message =
            "Slave server detection '"
                + slaveServerDetection.getSlaveServer().getName()
                + "' was replaced in the list.";
      } else {
        // replace the data in the old one...
        //
        SlaveServerDetection old = detections.get(index);
        old.setSlaveServer(slaveServerDetection.getSlaveServer());
        old.setActive(slaveServerDetection.isActive());

        // Note: in case it's not the slave server itself doing the sending, it might be possible
        // for it to be inactive...
        //
        if (old.isActive()) {
          old.setLastActiveDate(slaveServerDetection.getLastActiveDate());
        } else {
          old.setLastInactiveDate(slaveServerDetection.getLastInactiveDate());
        }
        message =
            "Slave server detection '"
                + slaveServerDetection.getSlaveServer().getName()
                + "' was added to the list.";
      }

      out.println(new WebResult(WebResult.STRING_OK, message));
    } catch (Exception ex) {
      out.println(new WebResult(WebResult.STRING_ERROR, Const.getStackTracker(ex)));
    }
  }