Ejemplo n.º 1
0
  /**
   * Maps a named servlet to a particular path or extension. If the named servlet is unregistered,
   * it will be added and subsequently mapped.
   *
   * <p>Note that the order of resolution to handle a request is:
   *
   * <p>exact mapped servlet (eg /catalog) prefix mapped servlets (eg /foo/bar/*) extension mapped
   * servlets (eg *jsp) default servlet
   */
  public void addServletMapping(String path, String servletName) throws TomcatException {
    if (mappings.get(path) != null) {
      log("Removing duplicate " + path + " -> " + mappings.get(path));
      mappings.remove(path);
      Container ct = (Container) containers.get(path);
      removeContainer(ct);
    }
    ServletWrapper sw = (ServletWrapper) servlets.get(servletName);
    if (sw == null) {
      // Workaround for frequent "bug" in web.xmls
      // Declare a default mapping
      log("Mapping with unregistered servlet " + servletName);
      sw = addServlet(servletName, servletName);
    }
    if ("/".equals(path)) defaultServlet = sw;

    mappings.put(path, sw);

    Container map = new Container();
    map.setContext(this);
    map.setHandler(sw);
    map.setPath(path);
    contextM.addContainer(map);
    containers.put(path, map);
  }
Ejemplo n.º 2
0
 private void initSetterMap() {
   Method setter = null;
   setter = getSetter("setKeyword", String.class);
   setMethodMap.put("keyword", setter);
   setter = getSetter("setParents", DefaultPersistibleList.class);
   setMethodMap.put("parentKeyword", setter);
   setter = getSetter("setDescribedInstances", DefaultPersistibleList.class);
   setMethodMap.put("describedInstances", setter);
   //  				setter = getSetter("getSubordinateKeywords");
   //  				getMethodMap.put("subordinateKeywords", setter);
 }
Ejemplo n.º 3
0
 private void initGetterMap() {
   Method getter = null;
   getter = getGetter("getKeyword");
   getMethodMap.put("keyword", getter);
   getter = getGetter("getParents");
   getMethodMap.put("parentKeyword", getter);
   getter = getGetter("getDescribedInstances");
   getMethodMap.put("describedInstances", getter);
   // 		getter = getGetter("getSubordinateKeywords");
   // 				getMethodMap.put("subordinateKeywords", getter);
 }
Ejemplo n.º 4
0
  private void addKeyword(Hashtable table, Keyword word, Keyword parent) {
    boolean recurse = true;

    if (table.containsKey(word)) recurse = false;

    if (parent == null) table.put(word, String.valueOf(-1));
    else table.put(word, parent);

    if (recurse) {
      Iterator it = word.getChildren().iterator();
      while (it.hasNext()) {
        addKeyword(table, (Keyword) it.next(), word);
      }
    }
  }
Ejemplo n.º 5
0
 /**
  * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_
  * indexed images. Images are cached: loading an image with the same name twice will get the
  * cached image the second time. If you want to remove an image from the cache, use purgeImage.
  * Throws JGError when there was an error.
  */
 @SuppressWarnings({"deprecation", "unchecked"})
 public JGImage loadImage(String imgfile) {
   Image img = (Image) loadedimages.get(imgfile);
   if (img == null) {
     URL imgurl = getClass().getResource(imgfile);
     if (imgurl == null) {
       try {
         File imgf = new File(imgfile);
         if (imgf.canRead()) {
           imgurl = imgf.toURL();
         } else {
           imgurl = new URL(imgfile);
           // throw new JGameError(
           //	"File "+imgfile+" not found.",true);
         }
       } catch (MalformedURLException e) {
         // e.printStackTrace();
         throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true);
       }
     }
     img = output_comp.getToolkit().createImage(imgurl);
     loadedimages.put(imgfile, img);
   }
   try {
     ensureLoaded(img);
   } catch (Exception e) {
     // e.printStackTrace();
     throw new JGameError("Error loading image " + imgfile);
   }
   return new JREImage(img);
 }
Ejemplo n.º 6
0
    public org.omg.CORBA.Contained[] lookup_name( String search_name, 
                                                  int levels_to_search, 
                                                  org.omg.CORBA.DefinitionKind limit_type, 
                                                  boolean exclude_inherited )
    {
        if( levels_to_search == 0 )
            return null;

        org.omg.CORBA.Contained[] c = contents( limit_type, exclude_inherited );
        Hashtable found = new Hashtable();

        for( int i = 0; i < c.length; i++)
            if( c[i].name().equals( search_name ) )
                found.put( c[i], "" );

        if( levels_to_search > 1 || levels_to_search == -1 )
        {
            // search up to a specific depth or undefinitely
            for( int i = 0; i < c.length; i++)
            {
                if( c[i] instanceof org.omg.CORBA.Container )
                {
                    org.omg.CORBA.Contained[] tmp_seq = 
                        ((org.omg.CORBA.Container)c[i]).lookup_name( search_name, 
                                                                     levels_to_search-1, 
                                                                     limit_type, 
                                                                     exclude_inherited);
                    if( tmp_seq != null )
                        for( int j = 0; j < tmp_seq.length; j++)
                            found.put( tmp_seq[j], "" );
                }
            } 			
        }

		
        org.omg.CORBA.Contained[] result = new org.omg.CORBA.Contained[ found.size() ];
        int idx = 0;

        for( Enumeration e = found.keys(); e.hasMoreElements(); )
            result[ idx++] = (org.omg.CORBA.Contained)e.nextElement();

        return result;
    }
Ejemplo n.º 7
0
 /**
  * Add a servlet with the given name to the container. The servlet will be loaded by the
  * container's class loader and instantiated using the given class name.
  *
  * <p>Called to add a new servlet from web.xml
  */
 public void addServlet(ServletWrapper wrapper) throws TomcatException {
   wrapper.setContext(this);
   String name = wrapper.getServletName();
   //	System.out.println("Adding servlet " + name  + " " + wrapper);
   // check for duplicates
   if (servlets.get(name) != null) {
     log("Removing duplicate servlet " + name + " " + wrapper);
     removeServletByName(name);
     //	    getServletByName(name).destroy();
   }
   servlets.put(name, wrapper);
 }
Ejemplo n.º 8
0
 /** Behaves like loadImage(String). Returns null if there was an error. */
 @SuppressWarnings("unchecked")
 public static JGImage loadImage(URL imgurl) {
   Image img = (Image) loadedimages.get(imgurl);
   if (img == null) {
     img = output_comp.getToolkit().createImage(imgurl);
     loadedimages.put(imgurl, img);
   }
   try {
     ensureLoaded(img);
   } catch (Exception e) {
     System.err.println("Error loading image " + imgurl);
     return null;
   }
   return new JREImage(img);
 }
Ejemplo n.º 9
0
  /** Look on disk for an editor with the class name 'ocName'. */
  PluggableEditor loadEditorFromDisk(String ocName) {
    // if here, we need to look on disk for a pluggable editor class...
    log.finer("looking for ocName: " + ocName);
    try {
      Class c = myLoader.loadClass(ocName);
      Constructor constructor = c.getConstructor(new Class[0]);

      // XXX If the pluggable editor has an error in the constructor, under some
      // XXX circumstances it can fail so badly that this call never returns, and
      // XXX the thread hangs!  It doesn't even get to the exception handler below...
      // XXX but sometimes if the constructor fails everything works as expected.  Wierd.
      PluggableEditor editor = (PluggableEditor) constructor.newInstance(new Object[0]);

      editors.put(ocName, editor); // add the new editor to our list
      return editor;
    } catch (Exception e) // expected condition - just means no pluggable editor available
    {
      if (e
          instanceof
          InvocationTargetException) // rare exception - an error was encountered in the plugin's
                                     // constructor.
      {
        log.warning("unable to load special editor for: '" + ocName + "' " + e);
        if (JXConfig.debugLevel >= 1) {
          log.warning("Error loading plugin class: ");
          ((InvocationTargetException) e).getTargetException().printStackTrace();
        }
      }

      log.log(Level.FINEST, "'Expected' Error loading " + ocName, e);
      editors.put(ocName, NONE); // add a blank place holder - we can't load
      // an editor for this, and there's no point looking again. (change if want dynamic loading,
      // i.e. look *every* time)
    }
    return null; // only here if an error has occured.
  }
Ejemplo n.º 10
0
  /**
   * Will add a new security constraint: For all paths: if( match(path) && match(method) && match(
   * transport ) ) then require("roles")
   *
   * <p>This is equivalent with adding a Container with the path, method and transport. If the
   * container will be matched, the request will have to pass the security constraints.
   */
  public void addSecurityConstraint(
      String path[], String methods[], String roles[], String transport) throws TomcatException {
    for (int i = 0; i < path.length; i++) {
      Container ct = new Container();
      ct.setContext(this);
      ct.setTransport(transport);
      ct.setRoles(roles);
      ct.setPath(path[i]);
      ct.setMethods(methods);

      // XXX check if exists, merge if true.
      constraints.put(path[i], ct);
      // contextM.addSecurityConstraint( this, path[i], ct);
      contextM.addContainer(ct);
    }
  }
Ejemplo n.º 11
0
  /**
   * When this class is loaded, preload the cache with a few items which we think will often be
   * needed. This can avoid the necessity of running a belief network context in simple problems.
   */
  static {
    System.err.println("PiHelperLoader.static: preload the helper cache.");

    helper_cache = new Hashtable();
    Vector seq = new Vector();

    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("pi", seq),
        riso.distributions.computes_pi.ConditionalDiscrete_Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda", seq), riso.distributions.computes_lambda.Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.AbstractDistribution.class);
    seq.addElement(riso.distributions.AbstractDistribution.class);

    helper_cache.put(
        new HelperCacheKey("pi_message", seq),
        riso.distributions.computes_pi_message.AbstractDistribution_AbstractDistribution.class);

    seq = new Vector();
    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda_message", seq),
        riso.distributions.computes_lambda_message.ConditionalDiscrete_Discrete_Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda_message", seq),
        riso.distributions.computes_lambda_message.ConditionalDiscrete_Discrete_.class);

    seq = new Vector();
    seq.addElement(riso.distributions.Discrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("posterior", seq),
        riso.distributions.computes_posterior.Discrete_Discrete.class);

    System.err.println("PiHelperLoader.static: helper_cache.size(): " + helper_cache.size());
  }
Ejemplo n.º 12
0
  /**
   * Returns an array containing all installed providers that satisfy the specified selection
   * criterion, or null if no such providers have been installed. The returned providers are ordered
   * according to their <a href= "#insertProviderAt(java.security.Provider, int)">preference
   * order</a>.
   *
   * <p>A cryptographic service is always associated with a particular algorithm or type. For
   * example, a digital signature service is always associated with a particular algorithm (e.g.,
   * DSA), and a CertificateFactory service is always associated with a particular certificate type
   * (e.g., X.509).
   *
   * <p>The selection criterion must be specified in one of the following two formats:
   *
   * <ul>
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type></i>
   *       <p>The cryptographic service name must not contain any dots.
   *       <p>A provider satisfies the specified selection criterion iff the provider implements the
   *       specified algorithm or type for the specified cryptographic service.
   *       <p>For example, "CertificateFactory.X.509" would be satisfied by any provider that
   *       supplied a CertificateFactory implementation for X.509 certificates.
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type> &lt;attribute_name>:&lt
   *       attribute_value></i>
   *       <p>The cryptographic service name must not contain any dots. There must be one or more
   *       space charaters between the the <i>&lt;algorithm_or_type></i> and the
   *       <i>&lt;attribute_name></i>.
   *       <p>A provider satisfies this selection criterion iff the provider implements the
   *       specified algorithm or type for the specified cryptographic service and its
   *       implementation meets the constraint expressed by the specified attribute name/value pair.
   *       <p>For example, "Signature.SHA1withDSA KeySize:1024" would be satisfied by any provider
   *       that implemented the SHA1withDSA signature algorithm with a keysize of 1024 (or larger).
   * </ul>
   *
   * <p>See Appendix A in the <a href= "../../../guide/security/CryptoSpec.html#AppA"> Java
   * Cryptogaphy Architecture API Specification &amp; Reference </a> for information about standard
   * cryptographic service names, standard algorithm names and standard attribute names.
   *
   * @param filter the criterion for selecting providers. The filter is case-insensitive.
   * @return all the installed providers that satisfy the selection criterion, or null if no such
   *     providers have been installed.
   * @throws InvalidParameterException if the filter is not in the required format
   * @throws NullPointerException if filter is null
   * @see #getProviders(java.util.Map)
   */
  public static Provider[] getProviders(String filter) {
    String key = null;
    String value = null;
    int index = filter.indexOf(':');

    if (index == -1) {
      key = filter;
      value = "";
    } else {
      key = filter.substring(0, index);
      value = filter.substring(index + 1);
    }

    Hashtable hashtableFilter = new Hashtable(1);
    hashtableFilter.put(key, value);

    return (getProviders(hashtableFilter));
  }
Ejemplo n.º 13
0
  private static Class getAdapterClass(
      Scriptable scope, Class superClass, Class[] interfaces, Scriptable obj) {
    ClassCache cache = ClassCache.get(scope);
    Hashtable generated = cache.javaAdapterGeneratedClasses;

    ObjToIntMap names = getObjectFunctionNames(obj);
    JavaAdapterSignature sig;
    sig = new JavaAdapterSignature(superClass, interfaces, names);
    Class adapterClass = (Class) generated.get(sig);
    if (adapterClass == null) {
      String adapterName = "adapter" + cache.newClassSerialNumber();
      byte[] code = createAdapterCode(names, adapterName, superClass, interfaces, null);

      adapterClass = loadAdapterClass(adapterName, code);
      if (cache.isCachingEnabled()) {
        generated.put(sig, adapterClass);
      }
    }
    return adapterClass;
  }
Ejemplo n.º 14
0
  /**
   * Reads the children of an XML element and matches them to properties of a bean.
   *
   * @param ob The bean to receive the values
   * @param element The element the corresponds to the bean
   * @throws IOException If there is an error reading the document
   */
  public void readObject(Object ob, Element element) throws IOException {
    // If the object is null, skip the element
    if (ob == null) {
      return;
    }

    try {
      BeanInfo info = (BeanInfo) beanCache.get(ob.getClass());

      if (info == null) {
        // Get the bean info for the object
        info = Introspector.getBeanInfo(ob.getClass(), Object.class);

        beanCache.put(ob.getClass(), info);
      }

      // Get the object's properties
      PropertyDescriptor[] props = info.getPropertyDescriptors();

      // Get the attributes of the node
      NamedNodeMap attrs = element.getAttributes();

      // Get the children of the XML element
      NodeList nodes = element.getChildNodes();

      int numNodes = nodes.getLength();

      for (int i = 0; i < props.length; i++) {
        // Treat indexed properties a little differently
        if (props[i] instanceof IndexedPropertyDescriptor) {
          readIndexedProperty(ob, (IndexedPropertyDescriptor) props[i], nodes, attrs);
        } else {
          readProperty(ob, props[i], nodes, attrs);
        }
      }
    } catch (IntrospectionException exc) {
      throw new IOException(
          "Error getting bean info for " + ob.getClass().getName() + ": " + exc.toString());
    }
  }
Ejemplo n.º 15
0
  private static Dictionary<String, Object> getDictionary(
      Map<String, Type> types, Map<String, Object> values) throws Exception {
    Hashtable<String, Object> ht = new Hashtable<String, Object>();
    for (Map.Entry<String, Object> e : values.entrySet()) {
      String key = e.getKey();
      Object value = e.getValue();

      Type type;
      if (types != null && (type = types.get(key)) != null) {

        if (type.scalar != null) {
          value = convert(value, type.scalar);
        } else if (type.vectorOf != null) {
          Collection<Object> coll = (Collection<Object>) value;
          Vector vector = new Vector();
          for (Object o : coll) {
            vector.add(convert(o, type.vectorOf));
          }
          value = vector;
        } else if (type.arrayOf != null) {
          if (value instanceof String && type.arrayOf.equals("byte")) {
            value = Base64.decodeBase64((String) value);
          } else {
            Collection<Object> coll = (Collection<Object>) value;
            Object array = Array.newInstance(getClass(type.arrayOf), coll.size());
            int n = 0;
            for (Object o : coll) {
              Array.set(array, n++, convert(o, type.arrayOf));
            }
            value = array;
          }
        } else {
          throw new IllegalArgumentException(
              "Key " + key + " has type but neither scalar, vectorOf, nor arrayOf is set");
        }
      }
      ht.put(key, value);
    }
    return ht;
  }
  /**
   * Creates a protocol provider for the given <tt>accountID</tt> and registers it in the bundle
   * context. This method has a persistent effect. Once created the resulting account will remain
   * installed until removed through the uninstallAccount method.
   *
   * @param accountID the account identifier
   * @return <tt>true</tt> if the account with the given <tt>accountID</tt> is successfully loaded,
   *     otherwise returns <tt>false</tt>
   */
  public boolean loadAccount(AccountID accountID) {
    // Need to obtain the original user id property, instead of calling
    // accountID.getUserID(), because this method could return a modified
    // version of the user id property.
    String userID = accountID.getAccountPropertyString(ProtocolProviderFactory.USER_ID);

    ProtocolProviderService service = createService(userID, accountID);

    Dictionary<String, String> properties = new Hashtable<String, String>();
    properties.put(PROTOCOL, protocolName);
    properties.put(USER_ID, userID);

    ServiceRegistration serviceRegistration =
        bundleContext.registerService(ProtocolProviderService.class.getName(), service, properties);

    if (serviceRegistration == null) return false;
    else {
      synchronized (registeredAccounts) {
        registeredAccounts.put(accountID, serviceRegistration);
      }
      return true;
    }
  }
Ejemplo n.º 17
0
    public org.omg.CORBA.Contained[] contents(org.omg.CORBA.DefinitionKind limit_type, 
                                              boolean exclude_inherited)
    {
        Hashtable limited = new Hashtable();

        // analog constants, exceptions etc.

        for( Enumeration e = contained.elements(); e.hasMoreElements();  )
        {
            org.omg.CORBA.Contained c = (org.omg.CORBA.Contained)e.nextElement();
            if( limit_type == org.omg.CORBA.DefinitionKind.dk_all || 
                limit_type == c.def_kind() )
            {
                limited.put( c, "" );
            }
        }

        org.omg.CORBA.Contained[] c = new org.omg.CORBA.Contained[limited.size()];
        int i;
        Enumeration e;
        for( e = limited.keys(), i=0 ; e.hasMoreElements(); i++ )
            c[i] = (org.omg.CORBA.Contained)e.nextElement();
        return c;			
    }
Ejemplo n.º 18
0
    public void loadContents()
    {
        // read from the  class (operations and atributes)
        Debug.assert( getReference() != null, "my own ref null");

        org.omg.CORBA.StructDef myReference = 
            org.omg.CORBA.StructDefHelper.narrow( getReference());

        Debug.assert( myReference != null, "narrow failed for " + getReference() );

        /* load nested definitions from interfacePackage directory */
        
        String[] classes = null;
        if( my_dir != null )
        {
            classes = my_dir.list( new IRFilenameFilter(".class") );

            // load class files in this interface's Package directory
            if( classes != null) 
            {
                for( int j = 0; j < classes.length; j++ )
                {
                    try 
                    { 
                        org.jacorb.util.Debug.output(2, "Struct " +name+ " tries " + 
                                                 full_name.replace('.', fileSeparator) + 
                                                 "Package" + fileSeparator + 
                                                 classes[j].substring( 0, classes[j].indexOf(".class")) );

                        ClassLoader loader = getClass().getClassLoader();
                        if( loader == null )
                        {
                            loader = RepositoryImpl.loader;
                        }

                        Class cl = 
                            loader.loadClass( 
                                             ( full_name.replace('.', fileSeparator) + "Package" + fileSeparator + 
                                               classes[j].substring( 0, classes[j].indexOf(".class"))
                                               ).replace( fileSeparator, '/') );
                        

                        Contained containedObject = Contained.createContained( cl, 
                                                                               path,
                                                                               myReference, 
                                                                               containing_repository );
                        if( containedObject == null )
                            continue;
                        
                        org.omg.CORBA.Contained containedRef = 
                            Contained.createContainedReference(containedObject);
                        
                        if( containedObject instanceof ContainerType )
                            ((ContainerType)containedObject).loadContents();
                        
                        containedRef.move( myReference, containedRef.name(), containedRef.version() );
                        
                        org.jacorb.util.Debug.output(2, "Struct " + full_name + 
                                                 " loads "+ containedRef.name() );
                        contained.put( containedRef.name() , containedRef );
                        containedLocals.put( containedRef.name(), containedObject );                        
                    } 
                    catch ( Exception e ) 
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
Ejemplo n.º 19
0
  /**
   * Sets the TabularData to the AaplicationTable
   *
   * @param data The TabularData to be set to the AaplicationTable
   */
  public void setAlarmTable(TabularData data) throws Exception {
    AgentException ae = null;

    for (Enumeration e = data.enumerate(); e.hasMoreElements(); ) {
      Object[] index = (Object[]) e.nextElement();
      CompositeData comp = data.getRow(index);

      if (table != null)
        entry =
            (AlarmEntry)
                Utilities.getEntryFromCompositeData(table, comp, indexNames, instrClassName);
      else if (vec != null)
        entry =
            (AlarmEntry) Utilities.getEntryFromCompositeData(vec, comp, indexNames, instrClassName);

      if (comp.getOperationType().equals(CompositeData.CREATED)) { // create new entry

        if (entry != null)
          throw new AgentException("Row already exist", CommonUtils.ROWCREATIONFAILED); // no i18n
        entry = new AlarmEntry();

        if (table != null) table.put(index, entry);
        else if (vec != null) vec.addElement(entry);
        for (Enumeration ce = comp.enumerate(); ce.hasMoreElements(); ) {
          String key = (String) ce.nextElement();
          try {
            Utilities.setField(entry, instrClassName, key, comp.getDataItem(key));
          } catch (AgentException aexp) {
            ae = aexp;
          }
        }
      } else if (comp.getOperationType().equals(CompositeData.DELETED)) {

        if (table != null) {
          for (Enumeration en = table.keys(); en.hasMoreElements(); ) {
            Object keyObject = en.nextElement();
            if (entry.equals(table.get(keyObject))) table.remove(keyObject);
          }
        } else if (vec != null)
          if (!vec.removeElement(entry))
            throw new AgentException("Invalid Index", CommonUtils.INVALIDINDEX); // no i18n
        data.deleteRow(index);
      } else if (comp.getOperationType().equals(CompositeData.MODIFIED)) {

        for (Enumeration ce = comp.enumerate(); ce.hasMoreElements(); ) {
          String key = (String) ce.nextElement();
          if (!comp.isModified(key)) continue;
          try {

            Utilities.setField(entry, instrClassName, key, comp.getDataItem(key));
          } catch (AgentException aexp) {
            ae = aexp;
          }
        }
      }

      comp.setOperationType(CompositeData.NOCHANGES);
    }

    if (ae != null) throw ae;
  }
Ejemplo n.º 20
0
  /** Sets up configuration based on params */
  private static boolean setup(Hashtable<String, String> curConf, Configuration argConf) {

    if (argConf.get("file") == null) {
      logger.fatal("Missing file parameter");
      System.exit(1);
    }

    if (argConf.get("hdfs_base_path") == null) {
      logger.fatal("Missing HDFS base path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("hdfs_temp_path") == null) {
      logger.fatal("Missing HDFS temp path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("local_temp_path") == null) {
      logger.fatal("Missing local temp path, check gestore-conf.xml");
      System.exit(1);
    }

    // Input paramaters
    curConf.put("run_id", argConf.get("run", ""));
    curConf.put("task_id", argConf.get("task", ""));
    curConf.put("file_id", argConf.get("file"));
    curConf.put("local_path", argConf.get("path", ""));
    curConf.put("type", argConf.get("type", "l2r"));
    curConf.put("timestamp_start", argConf.get("timestamp_start", "1"));
    curConf.put(
        "timestamp_stop", argConf.get("timestamp_stop", Integer.toString(Integer.MAX_VALUE)));
    curConf.put("delimiter", argConf.get("regex", "ID=.*"));
    curConf.put("taxon", argConf.get("taxon", "all"));
    curConf.put("intermediate", argConf.get("full_run", "false"));
    curConf.put("quick_add", argConf.get("quick_add", "false"));
    Boolean full_run = curConf.get("intermediate").matches("(?i).*true.*");
    curConf.put("format", argConf.get("format", "unknown"));
    curConf.put("split", argConf.get("split", "1"));
    curConf.put("copy", argConf.get("copy", "true"));

    // Constants
    curConf.put("base_path", argConf.get("hdfs_base_path"));
    curConf.put("temp_path", argConf.get("hdfs_temp_path"));
    curConf.put("local_temp_path", argConf.get("local_temp_path"));
    curConf.put("db_name_files", argConf.get("hbase_file_table"));
    curConf.put("db_name_runs", argConf.get("hbase_run_table"));
    curConf.put("db_name_updates", argConf.get("hbase_db_update_table"));

    // Timestamps
    Date currentTime = new Date();
    Date endDate = new Date(new Long(curConf.get("timestamp_stop")));
    curConf.put("timestamp_real", Long.toString(currentTime.getTime()));

    return true;
  }
Ejemplo n.º 21
0
 /** Initialize the opcodeArgTables table */
 static {
   opcodeArgTables = new Hashtable<String, int[]>();
   opcodeArgTables.put("CALL", new int[] {2});
   opcodeArgTables.put("INT", new int[] {1});
   opcodeArgTables.put("CDQ", new int[] {0});
   opcodeArgTables.put("CDO", new int[] {0});
   opcodeArgTables.put("CDQE", new int[] {0});
   opcodeArgTables.put("DIV", new int[] {1, 2});
   opcodeArgTables.put("IDIV", new int[] {1, 2});
   opcodeArgTables.put("MUL", new int[] {1, 2});
   opcodeArgTables.put("IMUL1", new int[] {1, 2});
   opcodeArgTables.put("DIV", new int[] {1, 2});
   opcodeArgTables.put("IDIV", new int[] {1, 2});
   opcodeArgTables.put("SET", new int[] {1, 0});
   opcodeArgTables.put("CMPXCHG", new int[] {1, 2});
   opcodeArgTables.put("CMPXCHG8B", new int[] {2});
   opcodeArgTables.put("FCMOV", new int[] {2, 0, 1});
   opcodeArgTables.put("CMOV", new int[] {2, 0, 1});
 }
Ejemplo n.º 22
0
  public int run(String[] args) throws Exception {
    // printUsage();
    /*
     * SETUP
     */
    Configuration argConf = getConf();
    Hashtable<String, String> confArg = new Hashtable<String, String>();
    setup(confArg, argConf);
    Date currentTime = new Date();
    Date endDate = new Date(new Long(confArg.get("timestamp_stop")));
    Boolean full_run = confArg.get("intermediate").matches("(?i).*true.*");
    Boolean quick_add = confArg.get("quick_add").matches("(?i).*true.*");
    logger.info("Running GeStore");

    // ZooKeeper setup
    Configuration config = HBaseConfiguration.create();
    zkWatcher = new ZooKeeperWatcher(config, "Testing", new HBaseAdmin(config));
    zkInstance =
        new ZooKeeper(
            ZKConfig.getZKQuorumServersString(config),
            config.getInt("zookeeper.session.timeout", -1),
            zkWatcher);

    if (!confArg.get("task_id").isEmpty()) {
      confArg.put("temp_path", confArg.get("temp_path") + confArg.get("task_id"));
    }

    String lockRequest = confArg.get("file_id");
    if (!confArg.get("run_id").isEmpty())
      lockRequest = lockRequest + "_" + confArg.get("run_id") + "_";
    if (!confArg.get("task_id").isEmpty())
      lockRequest = lockRequest + "_" + confArg.get("task_id") + "_";

    // Get type of movement
    toFrom type_move = checkArgs(confArg);
    if (type_move == toFrom.LOCAL2REMOTE && !confArg.get("format").equals("unknown")) {
      List<String> arguments = new ArrayList<String>();
      arguments.add("-Dinput=" + confArg.get("local_path"));
      arguments.add("-Dtable=" + confArg.get("file_id"));
      arguments.add("-Dtimestamp=" + confArg.get("timestamp_stop"));
      arguments.add("-Dtype=" + confArg.get("format"));
      arguments.add("-Dtarget_dir=" + confArg.get("base_path") + "_" + confArg.get("file_id"));
      arguments.add("-Dtemp_hdfs_path=" + confArg.get("temp_path"));
      arguments.add("-Drun_id=" + confArg.get("run_id"));
      if (!confArg.get("run_id").isEmpty()) arguments.add("-Drun_id=" + confArg.get("run_id"));
      if (!confArg.get("task_id").isEmpty()) arguments.add("-Dtask_id=" + confArg.get("task_id"));
      if (quick_add) arguments.add("-Dquick_add=" + confArg.get("quick_add"));
      String lockName = lock(lockRequest);
      String[] argumentString = arguments.toArray(new String[arguments.size()]);
      adddb.main(argumentString);
      unlock(lockName);
      System.exit(0);
    }

    // Database registration

    dbutil db_util = new dbutil(config);
    db_util.register_database(confArg.get("db_name_files"), true);
    db_util.register_database(confArg.get("db_name_runs"), true);
    db_util.register_database(confArg.get("db_name_updates"), true);
    FileSystem hdfs = FileSystem.get(config);
    FileSystem localFS = FileSystem.getLocal(config);

    // Get source type
    confArg.put("source", getSource(db_util, confArg.get("db_name_files"), confArg.get("file_id")));
    confArg.put(
        "database", isDatabase(db_util, confArg.get("db_name_files"), confArg.get("file_id")));
    if (!confArg.get("source").equals("local")
        && type_move == toFrom.REMOTE2LOCAL
        && !confArg.get("timestamp_stop").equals(Integer.toString(Integer.MAX_VALUE))) {
      confArg.put("timestamp_stop", Long.toString(latestVersion(confArg, db_util)));
    }

    /*
     * Get previous timestamp
     */
    Get run_id_get = new Get(confArg.get("run_id").getBytes());
    Result run_get = db_util.doGet(confArg.get("db_name_runs"), run_id_get);
    KeyValue run_file_prev =
        run_get.getColumnLatest(
            "d".getBytes(), (confArg.get("file_id") + "_db_timestamp").getBytes());
    String last_timestamp = new String("0");
    if (null != run_file_prev && !confArg.get("source").equals("local")) {
      long last_timestamp_real = run_file_prev.getTimestamp();
      Long current_timestamp = new Long(confArg.get("timestamp_real"));
      if ((current_timestamp - last_timestamp_real) > 36000) {
        last_timestamp = new String(run_file_prev.getValue());
        Integer lastTimestamp = new Integer(last_timestamp);
        lastTimestamp += 1;
        last_timestamp = lastTimestamp.toString();
        logger.info("Last timestamp: " + last_timestamp + " End data: " + endDate);
        Date last_run = new Date(run_file_prev.getTimestamp());
        if (last_run.before(endDate) && !full_run) {
          confArg.put("timestamp_start", last_timestamp);
        }
      }
    }

    Integer tse = new Integer(confArg.get("timestamp_stop"));
    Integer tss = new Integer(confArg.get("timestamp_start"));
    if (tss > tse) {
      logger.info("No new version of requested file.");
      return 0;
    }

    /*
     * Generate file
     */

    String lockName = lock(lockRequest);

    Get file_id_get = new Get(confArg.get("file_id").getBytes());
    Result file_get = db_util.doGet(confArg.get("db_name_files"), file_id_get);
    if (!file_get.isEmpty()) {
      boolean found =
          hasFile(
              db_util,
              hdfs,
              confArg.get("db_name_files"),
              confArg.get("file_id"),
              getFullPath(confArg));
      if (confArg.get("source").equals("fullfile")) {
        found = false;
      }
      String filenames_put =
          getFileNames(
              db_util, confArg.get("db_name_files"), confArg.get("file_id"), getFullPath(confArg));
      // Filename not found in file database
      if (!found && type_move == toFrom.REMOTE2LOCAL) {
        if (!confArg.get("source").equals("local")) {
          // Generate intermediate file
          if (getFile(hdfs, confArg, db_util) == null) {
            unlock(lockName);
            return 1;
          }
          // Put generated file into file database
          if (!confArg.get("format").equals("fullfile")) {
            putFileEntry(
                db_util,
                hdfs,
                confArg.get("db_name_files"),
                confArg.get("file_id"),
                confArg.get("full_file_name"),
                confArg.get("source"));
          }
        } else {
          logger.warn("Remote file not found, and cannot be generated! File: " + confArg);
          unlock(lockName);
          return 1;
        }
      }
    } else {
      if (type_move == toFrom.REMOTE2LOCAL) {
        logger.warn("Remote file not found, and cannot be generated.");
        unlock(lockName);
        return 1;
      }
    }

    /*
     * Copy file
     * Update tables
     */

    if (type_move == toFrom.LOCAL2REMOTE) {
      if (!confArg.get("format").equals("fullfile")) {
        putFileEntry(
            db_util,
            hdfs,
            confArg.get("db_name_files"),
            confArg.get("file_id"),
            getFullPath(confArg),
            confArg.get("source"));
      }
      putRunEntry(
          db_util,
          confArg.get("db_name_runs"),
          confArg.get("run_id"),
          confArg.get("file_id"),
          confArg.get("type"),
          confArg.get("timestamp_real"),
          confArg.get("timestamp_stop"),
          getFullPath(confArg),
          confArg.get("delimiter"));
      hdfs.copyFromLocalFile(new Path(confArg.get("local_path")), new Path(getFullPath(confArg)));
    } else if (type_move == toFrom.REMOTE2LOCAL) {
      FileStatus[] files = hdfs.globStatus(new Path(getFullPath(confArg) + "*"));
      putRunEntry(
          db_util,
          confArg.get("db_name_runs"),
          confArg.get("run_id"),
          confArg.get("file_id"),
          confArg.get("type"),
          confArg.get("timestamp_real"),
          confArg.get("timestamp_stop"),
          getFullPath(confArg),
          confArg.get("delimiter"));
      unlock(lockName);
      for (FileStatus file : files) {
        Path cur_file = file.getPath();
        Path cur_local_path =
            new Path(new String(confArg.get("local_path") + confArg.get("file_id")));
        String suffix = getSuffix(getFileName(confArg), cur_file.getName());
        if (suffix.length() > 0) {
          cur_local_path = cur_local_path.suffix(new String("." + suffix));
        }
        if (confArg.get("copy").equals("true")) {
          String crc = hdfs.getFileChecksum(cur_file).toString();
          if (checksumLocalTest(cur_local_path, crc)) {
            continue;
          } else {
            hdfs.copyToLocalFile(cur_file, cur_local_path);
            writeChecksum(cur_local_path, crc);
          }
        } else {
          System.out.println(cur_local_path + "\t" + cur_file);
        }
      }
    }
    unlock(lockName);
    return 0;
  }
Ejemplo n.º 23
0
  // Information needed to get a single file:
  // BASE_PATH, FILE_ID, TIMESTAMP_START, TIMESTAMP_STOP, SOURCE, FILESYSTEM
  private static Vector<Path> getFile(
      FileSystem fs, Hashtable<String, String> config, dbutil db_util) throws Exception {
    Long latestVersion = latestVersion(config, db_util);

    try {
      config.put("timestamp_start", config.get("timestamp_start"));
      config.put("timestamp_real", latestVersion.toString());
      config.put("timestamp_stop", latestVersion.toString());
    } catch (Exception E) {
      logger.error("Tryign to get file that is impossible to generate: " + getFullPath(config));
      return null;
    }
    if (Integer.parseInt(config.get("timestamp_start"))
        > Integer.parseInt(config.get("timestamp_stop"))) {
      return null;
    }
    logger.debug(
        "Getting DB for timestamp "
            + config.get("timestamp_start")
            + " to "
            + config.get("timestamp_stop"));

    String final_result = getFullPath(config);

    String temp_path_base =
        config.get("local_temp_path")
            + "_"
            + config.get("task_id")
            + "_"
            + config.get("run_id")
            + "/";
    Path newPath = new Path(final_result + "*");
    Vector<Path> ret_path = new Vector<Path>();
    String lockName = lock(final_result.replaceAll("/", "_"));
    if (fs.globStatus(newPath).length != 0) {
      ret_path.add(newPath);
      unlock(lockName);
      config.put("full_file_name", final_result);
      return ret_path;
    } else {
      if (!config.get("source").equals("local")) {
        config.put("temp_path_base", temp_path_base);

        config.put("timestamp_start", config.get("timestamp_start"));
        config.put("timestamp_real", latestVersion.toString());
        config.put("timestamp_stop", latestVersion.toString());

        Class<?> sourceClass =
            Class.forName("org.gestore.plugin.source." + config.get("source") + "Source");
        Method process_data = sourceClass.getMethod("process", Hashtable.class, FileSystem.class);
        Object processor = sourceClass.newInstance();
        Object retVal;
        try {
          retVal = process_data.invoke(processor, config, fs);
        } catch (InvocationTargetException E) {
          Throwable exception = E.getTargetException();
          logger.error("Unable to call method in child class: " + exception.toString());
          exception.printStackTrace(System.out);
          unlock(lockName);
          return null;
        }
        FileStatus[] files = (FileStatus[]) retVal;
        if (files == null) {
          logger.error("Error getting files, no files returned");
          return null;
        }

        for (FileStatus file : files) {
          Path cur_file = file.getPath();
          Path cur_local_path = new Path(temp_path_base + config.get("file_id"));
          String suffix = getSuffix(config.get("file_id"), cur_file.getName());
          cur_local_path = cur_local_path.suffix(suffix);
          Path res_path = new Path(new String(final_result + suffix));
          logger.debug("Moving file" + cur_file.toString() + " to " + res_path.toString());
          if (config.get("copy").equals("true")) {
            fs.moveFromLocalFile(cur_file, res_path);
          } else {
            fs.rename(cur_file, res_path);
          }
        }

        config.put("full_file_name", final_result);
      }
    }
    unlock(lockName);
    return ret_path;
  }
Ejemplo n.º 24
0
  /**
   * This method returns a <tt>Class</tt> for a helper which can handle the list of distributions
   * specified by <tt>seq1</tt>. We maintain a cache of recently-loaded helpers, so check the cache
   * before going to the trouble of searching for a helper. The cache is blown away every
   * <tt>HELPER_CACHE_REFRESH</tt> seconds.
   *
   * <p>If we can't find a helper in the cache, we must search through the list of available helpers
   * to find an appropriate one. First try to find helper using class sequence as specified by
   * <tt>seq</tt>. Whether or not that succeeds, promote any <tt>Gaussian</tt> in the sequence to
   * <tt>MixGaussians</tt>, and try again. If we get a better match on the second try, return the
   * helper thus found.
   */
  public static Class find_helper_class(Vector seq1, String helper_type)
      throws ClassNotFoundException {
    // Let's see if an appropriate helper is in the cache.
    // If the cache is too old, empty it and search for the helper anew.

    if (System.currentTimeMillis() - cache_timestamp > HELPER_CACHE_REFRESH) {
      helper_cache = new Hashtable();
      cache_timestamp = System.currentTimeMillis();
      // Go on and search for appropriate helper.
    } else {
      HelperCacheKey key = new HelperCacheKey(helper_type, seq1);
      Class helper_class = (Class) helper_cache.get(key);
      if (helper_class != null) {
        if (Global.debug > -1)
          System.err.println(
              "PiHelperLoader.find_helper_class: found helper class: "
                  + helper_class
                  + "; no need to search.");
        return helper_class;
      }
      // else no luck; we have to search for helper.
    }

    // Well, we didn't find a helper in the cache, so let's go to work.
    if (Global.debug > -1)
      System.err.println(
          "PiHelperLoader.find_helper_class: DID NOT FIND HELPER CLASS; NOW SEARCH.");

    Class c1 = null, c2 = null;
    ClassNotFoundException cnfe1 = null, cnfe2 = null;
    int[] class_score1 = new int[1], count_score1 = new int[1];
    int[] class_score2 = new int[1], count_score2 = new int[1];

    try {
      c1 = find_helper_class1(seq1, helper_type, class_score1, count_score1);
    } catch (ClassNotFoundException e) {
      cnfe1 = e;
    } // hang on, we may need to re-throw later.

    Class gaussian_class = Class.forName("riso.distributions.Gaussian");
    MixGaussians mog = new MixGaussians(1, 1);

    Vector seq2 = new Vector(seq1.size());
    for (int i = 0; i < seq1.size(); i++)
      if (gaussian_class.isAssignableFrom((Class) seq1.elementAt(i)))
        seq2.addElement(mog.getClass());
      else seq2.addElement(seq1.elementAt(i));

    try {
      c2 = find_helper_class1(seq2, helper_type, class_score2, count_score2);
    } catch (ClassNotFoundException e) {
      cnfe2 = e;
    }

    if (cnfe1 == null && cnfe2 == null) {
      // Both matched; see which one fits better.
      // Break ties in favor of the helper for non-promoted messages.

      if (class_score1[0] >= class_score2[0]
          || (class_score1[0] == class_score2[0] && count_score1[0] >= count_score2[0])) {
        if (Global.debug > 1)
          System.err.println(
              "\taccept helper " + c1 + " for non-promoted classes instead of " + c2);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
        return c1;
      } else {
        if (Global.debug > 1)
          System.err.println("\taccept helper " + c2 + " for promoted classes instead of " + c1);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
        return c2;
      }
    } else if (cnfe1 == null && cnfe2 != null) {
      // Only the first try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
      return c1;
    } else if (cnfe1 != null && cnfe2 == null) {
      // Only the second try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
      return c2;
    } else {
      // Neither try matched. Re-throw the exception generated by the first try.
      throw cnfe1;
    }
  }
Ejemplo n.º 25
0
  public static void main(String arg[]) {
    Hashtable ignoreList = new Hashtable();
    Class cl = null;
    Model model = null;
    System.out.println("Synchronizing forms with database...");
    Db.init();

    try {
      DatabaseMetaData meta = Db.getCon().getMetaData();
      String[] types = {"TABLE"};
      ResultSet rs = meta.getTables(null, null, "%", types);

      // read ignore.list
      ignoreList = AutogenerateUtil.readIgnoreList();
      // prepare directory
      File fDir = new File("../../web/WEB-INF/views/crud_form");
      if (!fDir.exists()) fDir.mkdir();
      while (rs.next()) {
        // proper file name generationm
        String className = "";
        String tableName = rs.getString("TABLE_NAME");
        className = StringUtil.toProperClassName(tableName); // space allowed...
        // tableName = tableName.toUpperCase(); //If Oracle that need uppercase tablename. In MySQL
        // in Mac OS X (and probably Linux), it mustbe case sensitive
        // open table
        String sql = "select * from " + tableName;
        PreparedStatement pstmt =
            Db.getCon()
                .prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();

        // get foreign keys,and stored it in hashtable
        ResultSet rsFk = meta.getImportedKeys(Db.getCon().getCatalog(), null, tableName);
        Hashtable hashFk = new Hashtable();
        System.out.println("FK Infos for table " + tableName);
        while (rsFk.next()) {
          String pkTableName = rsFk.getString("PKTABLE_NAME");
          String pkColumnName = rsFk.getString("PKCOLUMN_NAME");
          String fkColumnName = rsFk.getString("FKCOLUMN_NAME");

          int fkSequence = rsFk.getInt("KEY_SEQ");
          System.out.println(
              tableName + "." + fkColumnName + " => " + pkTableName + "." + pkColumnName);
          hashFk.put(fkColumnName, pkColumnName);
          hashFk.put(fkColumnName + "_table", pkTableName);
        }
        rsFk.close();

        // create form page
        System.out.println(
            "Creating form page for "
                + tableName
                + " from table + "
                + application.config.Database.DB
                + "."
                + tableName);
        fDir = new File("../../web/WEB-INF/views/" + tableName);
        if (!fDir.exists()) fDir.mkdir();
        File f = new File("../../web/WEB-INF/views/" + tableName + "/form_" + tableName + ".jsp");
        if (ignoreList.get("form_" + tableName + ".jsp") != null) {
          Logger.getLogger(GenerateForm.class.getName())
              .log(Level.INFO, "Ignoring creation of form_" + tableName + ".jsp");
        } else {
          Writer out = new FileWriter(f);
          out.write(
              "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>");
          out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n");
          out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n");

          // create model for this class, use in detecting its PK Field
          cl = Class.forName("application.models." + className + "Model");
          model = (Model) cl.newInstance();

          // iterate all columns
          resultSet.beforeFirst();
          resultSet.next();
          out.write(
              "<table border=\"1\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" bordercolor=\"#E8EDFF\">\n");
          out.write("<tr>\n");
          out.write("<td>\n");
          out.write(
              "<form action=\"<%=Config.base_url%>index/"
                  + className
                  + "/save\" method=\"post\" enctype=\"multipart/form-data\">\n"); // I hope it's
          // okay to
          // default it to
          // multipart data
          out.write("<table id=\"hor-zebra\" summary=\"Form " + className + "\">\n");
          out.write("<thead>\n");
          out.write("<tr>\n");
          out.write("<th colspan=\"2\" class=\"odd\" scope=\"col\">Form " + className + " </th>\n");
          out.write("</tr>\n");
          out.write("</thead>\n");
          out.write("<tbody>\n");

          for (int i = 1; i <= nColoumn; i++) {
            String columnName = metaColumn.getColumnName(i);
            String dataType = metaColumn.getColumnClassName(i);
            out.write("<tr>\n");

            // if(!columnName.equals(model.getPkFieldName())) // implementing the case of PK not
            // AutoIncrement
            // if(!metaColumn.isAutoIncrement(i))
            // {
            // varying field input for type

            // foreign field, as chooser page view
            if (hashFk.get(columnName)
                != null) // TODO: what if PK is chooser also?? :) CUrrently I add it manually the
            // hidden_*Pk_nama* field
            {
              String fkTableName = hashFk.get(columnName + "_table") + "";
              String fkColumnName = hashFk.get(columnName) + "";
              String fkController = StringUtil.toProperClassName(fkTableName);

              out.write("<td>" + columnName + "</td>\n");
              out.write("<td>\n");
              out.write(
                  "<input name=\""
                      + columnName
                      + "\" type=\"hidden\" id=\""
                      + columnName
                      + "\" value=\"${model."
                      + columnName
                      + "}\"/>\n");
              out.write(
                  "<input name=\"label_"
                      + columnName
                      + "\" readonly=\"true\" type=\"text\" id=\"label_"
                      + columnName
                      + "\" value=\"${model."
                      + columnName
                      + "}\"/>\n"); // TODO : translate I
              out.write(
                  "<a href=\"<%=Config.base_url%>index/"
                      + fkController
                      + "/chooseView?height=220&width=700\" class=\"thickbox\">Pilih</a>");
              out.write("</td>\n");
            } else {

              // regular field input, not foreign key case
              if (!columnName.equals(model.getPkFieldName())) {
                out.write("<td>" + columnName + "</td>\n");
                out.write("<td>\n");

                // ENUM Column, displayed as HTML SELECT. May will only work for mysql only...
                Logger.getLogger(GenerateForm.class.getName())
                    .log(Level.INFO, columnName + " type is " + metaColumn.getColumnType(i));
                if (metaColumn.getColumnType(i) == 1) {
                  String enum_content[][] =
                      Db.getDataSet(
                          "SELECT SUBSTRING(COLUMN_TYPE,6,length(SUBSTRING(COLUMN_TYPE,6))-1) as enum_content "
                              + " FROM information_schema.COLUMNS "
                              + " WHERE TABLE_NAME='"
                              + tableName
                              + "' "
                              + " AND COLUMN_NAME='"
                              + columnName
                              + "'");
                  if (enum_content.length > 0) {
                    // Logger.getLogger(Model.class.getName()).log(Level.INFO, "Enum Content = " +
                    // enum_content[0][0]);
                    String enum_list[] = enum_content[0][0].split(",");
                    out.write("<select name=\"" + columnName + "\" id=\"" + columnName + "\">\n");
                    for (int ienum_list = 0; ienum_list < enum_list.length; ienum_list++)
                      out.write(
                          "\t<option <c:if test=\"${model."
                              + columnName
                              + "=='"
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "'}\"> selected=\"selected\" </c:if> value=\""
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "\">"
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "</option>\n");
                    out.write("</select>\n\n");

                  } else {
                    // no enum content detected.. :)
                    out.write(
                        "<input name=\""
                            + columnName
                            + "\" type=\"text\" id=\""
                            + columnName
                            + "\" value=\"${model."
                            + columnName
                            + "}\"/>\n");
                  }
                } else if (metaColumn.getColumnType(i) == 91) {
                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("<script>\n");
                  out.write(
                      " if(!isValidDate($('#"
                          + columnName
                          + "').val())) $('#"
                          + columnName
                          + "').val('1980-1-1');\n"); // TODO: default value
                  out.write("  (function($){\n");

                  out.write("  $('#" + columnName + "').click(function() {\n");
                  out.write("    $('#" + columnName + "').DatePickerShow();\n");
                  out.write("  });\n");

                  out.write("  $('#" + columnName + "').DatePicker({\n");
                  out.write("    format:'Y-m-d',\n");
                  out.write("    date: $('#" + columnName + "').val(),\n");
                  out.write("    current: $('#" + columnName + "').val(),\n");
                  out.write("    starts: 1,\n");
                  out.write("    position: 'r',\n");

                  out.write("    onBeforeShow: function(){\n");
                  out.write(
                      "      $('#"
                          + columnName
                          + "').DatePickerSetDate($('#"
                          + columnName
                          + "').val(), true);\n");
                  out.write("    },\n");

                  out.write("    onChange: function(formated, dates){\n");
                  out.write("      $('#" + columnName + "').DatePickerHide();\n");
                  out.write("      $('#" + columnName + "').val(formated);\n");
                  out.write("    }\n");
                  out.write("  });\n");
                  out.write("  })(jQuery)\n");
                  out.write(" </script>\n");
                } else {
                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("${" + columnName + "_error}\n"); // regular input field
                }
              } else { // PK case
                if (metaColumn.isAutoIncrement(i)) {
                  out.write(
                      "<input name=\"hidden_"
                          + columnName
                          + "\" type=\"hidden\" id=\"hidden_"
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                } else {
                  out.write("<td>" + columnName + "</td>\n");
                  out.write("<td>\n");

                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("${" + columnName + "_error}\n");
                  out.write(
                      "<input name=\"hidden_"
                          + columnName
                          + "\" type=\"hidden\" id=\"hidden_"
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                }
              }
              out.write("</td>\n");
            }
            out.write("</tr>\n");
          }
          out.write("<tr class=\"odd\">\n");
          out.write("<td>&nbsp;</td>\n");
          out.write("<td><input type=\"submit\" name=\"Submit\" value=\"Simpan\">");
          out.write(
              "<input name=\"Button\" type=\"button\" id=\"Submit\" value=\"Batal\" onClick=\"javascript:history.back(-1);\"></td>\n");
          out.write("</tr>\n");
          out.write("</tbody>\n");
          out.write("</table>\n");
          out.write("</form></td>\n");
          out.write("</tr>\n");
          out.write("</table>\n");
          out.flush();
          out.close();
        }

        // create viewPage
        if (ignoreList.get("view_" + tableName + ".jsp") != null) {
          Logger.getLogger(GenerateForm.class.getName())
              .log(Level.INFO, "Ignoring creation of view_" + tableName + ".jsp");
        } else {
          System.out.println("Creating view page " + tableName);

          fDir = new File("../../web/WEB-INF/views/" + tableName);
          if (!fDir.exists()) fDir.mkdir();
          File fView =
              new File("../../web/WEB-INF/views/" + tableName + "/view_" + tableName + ".jsp");
          Writer outView = new FileWriter(fView);
          outView.write(
              "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>");
          outView.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n");
          outView.write(
              "<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n");
          outView.write("<% int pagenum = 0; %>\n");
          // outView.write("<%@ include file=\"/WEB-INF/views/header.jsp\" %>");
          outView.write(
              "<a href=\"<%=Config.base_url%>index/" + className + "/input/-1\">Tambah Data</a>\n");
          outView.write(
              "|| <a href=\"<%=Config.base_url%>index/" + className + "/print\">Cetak</a>\n");
          outView.write("<table width=\"100%\" id=\"rounded-corner\">\n");
          outView.write("<thead>\n");
          // iterate all columns : table header
          outView.write("  <tr>\n");
          outView.write("  <th scope=\"col\" class=\"rounded-company\">No.</th>\n");
          resultSet.beforeFirst();
          resultSet.next();

          // get Primary Key Field Name : often use
          String pkFieldName = "";
          try {
            Class params[] = null;
            Method objMethod = cl.getMethod("getPkFieldName", params);
            pkFieldName = "" + objMethod.invoke(model);
          } catch (Exception ex) {
            Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
          }

          // ALL Lower Case
          pkFieldName = pkFieldName.toLowerCase();

          // customize column view page
          for (int i = 1; i <= nColoumn; i++) {
            String columnName =
                metaColumn.getColumnName(i).toLowerCase(); // Caution : ALL LowerCase
            String dataType = metaColumn.getColumnClassName(i);
            String thClass = "rounded-q1";
            String thTitle = StringUtil.toProperFieldTitle(columnName);

            if (TableCustomization.getTable(tableName)
                != null) // there is customization for this table
            {
              if (TableCustomization.getTable(tableName).get(columnName) != null) {
                thTitle = TableCustomization.getTable(tableName).get(columnName) + "";
                outView.write(
                    "  <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n");
              }
            } else { // standard view for this table : hide PK, because mostly is auto increment
              if (!metaColumn.isAutoIncrement(i))
                outView.write(
                    "  <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n");
            }
          }

          outView.write("  <th scope=\"col\" class=\"rounded-q4\">Aksi</th>\n");
          outView.write("  </tr>\n");
          outView.write("</thead>\n");
          outView.write("<tfoot>\n");
          outView.write("  <tr>\n");
          outView.write(
              "    <td colspan=\""
                  + (nColoumn + 1)
                  + "\" class=\"rounded-foot-left\"><%=Pagination.createLinks(pagenum)%></td>\n");
          outView.write("    <td class=\"rounded-foot-right\">&nbsp;</td>\n");
          outView.write("  </tr>\n");
          outView.write("</tfoot>\n");

          outView.write("<tbody>\n");
          outView.write("  <c:forEach items=\"${row}\" var=\"item\" varStatus=\"status\" >\n");
          outView.write("    <tr>\n");
          outView.write("      <td>${status.count}</td>\n");

          // iterate all columns : table data
          resultSet.beforeFirst();
          resultSet.next();
          for (int i = 1; i <= nColoumn; i++) {
            String columnName = metaColumn.getColumnName(i);
            // if(!columnName.equals(pkFieldName)) //TOFIX : currently, PK Field is not shown
            if (TableCustomization.getTable(tableName) != null) {
              if (TableCustomization.getTable(tableName).get(columnName) != null) {
                outView.write("      <td>${item." + columnName + "}</td>\n");
              }
            } else {
              if (!metaColumn.isAutoIncrement(i))
                outView.write("      <td>${item." + columnName + "}</td>\n");
            }
          }

          outView.write("      <td>\n");
          outView.write(
              "         <a href=\"<%=Config.base_url%>index/"
                  + className
                  + "/input/${item."
                  + pkFieldName
                  + "}\">Ubah</a>\n");
          outView.write(
              "         <a href=\"<%=Config.base_url%>index/"
                  + className
                  + "/delete/${item."
                  + pkFieldName
                  + "}\" onClick=\"return confirm('Apakah Anda yakin?');\">Hapus</a>\n");
          outView.write("      </td>\n");

          outView.write("    </tr>\n");
          outView.write("  </c:forEach>\n");
          outView.write("</tbody>\n");
          outView.write("</table>\n");
          // outView.write("<%@ include file=\"/WEB-INF/views/footer.jsp\" %>");
          outView.flush();
          outView.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 26
0
 public void setAttribute(String name, Object object) {
   attributes.put(name, object);
 }
Ejemplo n.º 27
0
 public void addInitParameter(String name, String value) {
   initializationParameters.put(name, value);
 }
Ejemplo n.º 28
0
 /** Add Env-entry to this context */
 public void addEnvEntry(String name, String type, String value, String description) {
   System.out.println("Add env-entry " + name + "  " + type + " " + value + " " + description);
   if (name == null || type == null) throw new IllegalArgumentException();
   envEntryTypes.put(name, type);
   if (value != null) envEntryValues.put(name, value);
 }
Ejemplo n.º 29
0
 /** Add a taglib declaration for this context */
 public void addTaglib(String uri, String location) {
   //	System.out.println("Add taglib " + uri + "  " + location );
   tagLibs.put(uri, location);
 }
Ejemplo n.º 30
0
  /**
   * Analyze class fields and fill in "voSetterMethods","voGetterMethods","indexes",reverseIndexes"
   * attributes.
   *
   * @param prefix e.g. "attrx.attry."
   * @param parentMethods getter methods of parent v.o.
   * @param classType class to analyze
   */
  private void analyzeClassFields(String prefix, Method[] parentMethods, Class classType) {
    try {
      if (prefix.split("\\.").length > ClientSettings.MAX_NR_OF_LOOPS_IN_ANALYZE_VO) return;

      // retrieve all getter and setter methods defined in the specified value object...
      String attributeName = null;
      Method[] methods = classType.getMethods();
      String aName = null;
      for (int i = 0; i < methods.length; i++) {
        attributeName = methods[i].getName();

        if (attributeName.startsWith("get")
            && methods[i].getParameterTypes().length == 0
            && ValueObject.class.isAssignableFrom(methods[i].getReturnType())) {
          aName = getAttributeName(attributeName, classType);
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          analyzeClassFields(prefix + aName + ".", newparentMethods, methods[i].getReturnType());
        }

        if (attributeName.startsWith("get")
            && methods[i].getParameterTypes().length == 0
            && (methods[i].getReturnType().equals(String.class)
                || methods[i].getReturnType().equals(Long.class)
                || methods[i].getReturnType().equals(Long.TYPE)
                || methods[i].getReturnType().equals(Float.class)
                || methods[i].getReturnType().equals(Float.TYPE)
                || methods[i].getReturnType().equals(Short.class)
                || methods[i].getReturnType().equals(Short.TYPE)
                || methods[i].getReturnType().equals(Double.class)
                || methods[i].getReturnType().equals(Double.TYPE)
                || methods[i].getReturnType().equals(BigDecimal.class)
                || methods[i].getReturnType().equals(java.util.Date.class)
                || methods[i].getReturnType().equals(java.sql.Date.class)
                || methods[i].getReturnType().equals(java.sql.Timestamp.class)
                || methods[i].getReturnType().equals(Integer.class)
                || methods[i].getReturnType().equals(Integer.TYPE)
                || methods[i].getReturnType().equals(Character.class)
                || methods[i].getReturnType().equals(Boolean.class)
                || methods[i].getReturnType().equals(boolean.class)
                || methods[i].getReturnType().equals(ImageIcon.class)
                || methods[i].getReturnType().equals(Icon.class)
                || methods[i].getReturnType().equals(byte[].class)
                || methods[i].getReturnType().equals(Object.class)
                || ValueObject.class.isAssignableFrom(methods[i].getReturnType()))) {
          attributeName = getAttributeName(attributeName, classType);
          //          try {
          //            if
          // (classType.getMethod("set"+attributeName.substring(0,1).toUpperCase()+attributeName.substring(1),new Class[]{methods[i].getReturnType()})!=null)
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          voGetterMethods.put(prefix + attributeName, newparentMethods);
          //          } catch (NoSuchMethodException ex) {
          //          }
        } else if (attributeName.startsWith("is")
            && methods[i].getParameterTypes().length == 0
            && (methods[i].getReturnType().equals(Boolean.class)
                || methods[i].getReturnType().equals(boolean.class))) {
          attributeName = getAttributeName(attributeName, classType);
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          voGetterMethods.put(prefix + attributeName, newparentMethods);
        } else if (attributeName.startsWith("set") && methods[i].getParameterTypes().length == 1) {
          attributeName = getAttributeName(attributeName, classType);
          try {
            if (classType.getMethod(
                    "get"
                        + attributeName.substring(0, 1).toUpperCase()
                        + attributeName.substring(1),
                    new Class[0])
                != null) {
              Method[] newparentMethods = new Method[parentMethods.length + 1];
              System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
              newparentMethods[parentMethods.length] = methods[i];
              voSetterMethods.put(prefix + attributeName, newparentMethods);
            }
          } catch (NoSuchMethodException ex) {
            try {
              if (classType.getMethod(
                      "is"
                          + attributeName.substring(0, 1).toUpperCase()
                          + attributeName.substring(1),
                      new Class[0])
                  != null) {
                Method[] newparentMethods = new Method[parentMethods.length + 1];
                System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
                newparentMethods[parentMethods.length] = methods[i];
                voSetterMethods.put(prefix + attributeName, newparentMethods);
              }
            } catch (NoSuchMethodException exx) {
            }
          }
        }
      }

      // fill in indexes with the colProperties indexes first; after them, it will be added the
      // other indexes (of attributes not mapped with grid column...)
      HashSet alreadyAdded = new HashSet();
      int i = 0;
      for (i = 0; i < colProperties.length; i++) {
        indexes.put(new Integer(i), colProperties[i].getColumnName());
        reverseIndexes.put(colProperties[i].getColumnName(), new Integer(i));
        alreadyAdded.add(colProperties[i].getColumnName());
      }
      Enumeration en = voGetterMethods.keys();
      while (en.hasMoreElements()) {
        attributeName = en.nextElement().toString();
        if (!alreadyAdded.contains(attributeName)) {
          indexes.put(new Integer(i), attributeName);
          reverseIndexes.put(attributeName, new Integer(i));
          i++;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }