private void fixNullOutputsForSOAP(CrownCounselIndexGetList_Properties fromClient) {
   // Transform null to "null"
   Class c = fromClient.getClass();
   java.beans.BeanInfo beanInfo = null;
   try {
     beanInfo = java.beans.Introspector.getBeanInfo(c);
   } catch (Exception e) {
   }
   java.beans.PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
   for (int i = 0; i < properties.length; i++) {
     java.beans.PropertyDescriptor property = properties[i];
     java.lang.reflect.Method readMethod = property.getReadMethod();
     java.lang.reflect.Method writeMethod = property.getWriteMethod();
     if ((readMethod != null) && (writeMethod != null)) {
       String currentvalue = new String("");
       if (readMethod.getReturnType() == currentvalue.getClass()) {
         try {
           currentvalue = (String) (readMethod.invoke(fromClient, null));
         } catch (java.lang.reflect.InvocationTargetException a1) // Null argument
         {
           try {
             Object[] args1 = new Object[1];
             args1[0] = new String("null");
             writeMethod.invoke(fromClient, args1);
           } catch (Exception e2) {
           }
         } catch (Exception e1) {
         }
       } else {
       }
     }
   }
 }
Example #2
0
 private VirtualMachine createVirtualMachine(Class virtualMachineImplClass, int pid)
     throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
   java.lang.reflect.Method createByPIDMethod =
       virtualMachineImplClass.getMethod(
           "createVirtualMachineForPID",
           new Class[] {VirtualMachineManager.class, Integer.TYPE, Integer.TYPE});
   return (VirtualMachine)
       createByPIDMethod.invoke(
           null,
           new Object[] {Bootstrap.virtualMachineManager(), new Integer(pid), new Integer(0)});
 }
Example #3
0
 private static final org.openide.nodes.CookieSet getCookieSet(MultiDataObject obj) {
   try {
     if (getCookieSetMethod == null) {
       getCookieSetMethod =
           MultiDataObject.class.getDeclaredMethod("getCookieSet", new Class[] {}); // NOI18N
       getCookieSetMethod.setAccessible(true);
     }
     return (org.openide.nodes.CookieSet) getCookieSetMethod.invoke(obj, new Object[] {});
   } catch (Exception e) {
     ErrorManager.getDefault().notify(e);
     return new org.openide.nodes.CookieSet();
   }
 }
 private void fixNullInputsForSOAP(CrownCounselIndexGetList_Properties fromClient) {
   // Transform "null" to null
   // Set hPubStartPoolName and hPubLinkKey to null if string < 1
   Class c = fromClient.getClass();
   java.beans.BeanInfo beanInfo = null;
   try {
     beanInfo = java.beans.Introspector.getBeanInfo(c);
   } catch (Exception e) {
   }
   java.beans.PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
   for (int i = 0; i < properties.length; i++) {
     java.beans.PropertyDescriptor property = properties[i];
     java.lang.reflect.Method readMethod = property.getReadMethod();
     java.lang.reflect.Method writeMethod = property.getWriteMethod();
     if ((readMethod != null) && (writeMethod != null)) {
       String currentvalue = new String("");
       if (readMethod.getReturnType() == currentvalue.getClass()) {
         try {
           currentvalue = (String) readMethod.invoke(fromClient, null);
         } catch (Exception e1) {
         }
         if (currentvalue != null) {
           if (currentvalue.equals("null")) {
             try {
               Object[] args1 = new Object[1];
               args1[0] = null;
               writeMethod.invoke(fromClient, args1);
             } catch (Exception e2) {
             }
           }
           if ((currentvalue.length() < 1 || currentvalue.endsWith("/null"))
               && (writeMethod.getName().indexOf("PubStartPoolName") > -1)) {
             try {
               Object[] args1 = new Object[1];
               args1[0] = "ICONEJB/null";
               writeMethod.invoke(fromClient, args1);
             } catch (Exception e2) {
             }
           }
           if ((currentvalue.length() < 1) && (writeMethod.getName().indexOf("PubLinkKey") > -1)) {
             try {
               Object[] args1 = new Object[1];
               args1[0] = null;
               writeMethod.invoke(fromClient, args1);
             } catch (Exception e2) {
             }
           }
         }
       } else {
       }
     }
   }
 }
Example #5
0
 public static Cookie getSSOToken() {
   if (GET_SSO_METHOD == null && !GET_SSO_METHOD_INITIALIZED) {
     try {
       GET_SSO_METHOD_INITIALIZED = true;
       GET_SSO_METHOD = TransportHttp.class.getMethod("getSSOToken");
     } catch (RuntimeException e) {
       //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
       // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "RuntimeException while trying to look up
       // JGit call", e));
     } catch (NoSuchMethodException e) {
       //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
       // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NoSuchMethodException while trying to look
       // up JGit call", e));
     }
   }
   if (GET_SSO_METHOD != null) {
     try {
       return (Cookie) GET_SSO_METHOD.invoke(null);
     } catch (IllegalArgumentException e) {
       //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
       // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IllegalArgumentException while trying to
       // set token", e));
     } catch (IllegalAccessException e) {
       //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
       // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IllegalAccessException while trying to set
       // token", e));
     } catch (InvocationTargetException e) {
       //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
       // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InvocationTargetException while trying to
       // set token", e));
     }
   }
   return null;
 }
  // TODO remove suppression
  @SuppressWarnings({"unchecked", "rawtypes"})
  private List<AnnotationResolver> getAnnotationResolvers(
      final GeneratorContext context, final TreeLogger logger) {
    java.lang.reflect.Method m = null;
    ArrayList args = new ArrayList();
    ArrayList types = new ArrayList();

    types.add(GeneratorContext.class);
    args.add(context);
    types.add(TreeLogger.class);
    args.add(logger);

    Object[] argValues = args.toArray();
    Class[] argtypes = (Class[]) types.toArray(new Class[argValues.length]);

    try {
      m = BINDING_DEFAULTS.getMethod("getAnnotationResolvers", argtypes);
    } catch (SecurityException e) {
      throw new RuntimeException(
          "could not call method `getAnnotationResolvers´ on " + BINDING_DEFAULTS, e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(
          "could not resolve method `getAnnotationResolvers´ on " + BINDING_DEFAULTS, e);
    }

    List<AnnotationResolver> l = new ArrayList<AnnotationResolver>();
    try {
      l = (List<AnnotationResolver>) m.invoke(null, context, logger);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException(
          "could not call method `getAnnotationResolvers´ on " + BINDING_DEFAULTS, e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(
          "could not call method `getAnnotationResolvers´ on " + BINDING_DEFAULTS, e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(
          "could not call method `getAnnotationResolvers´ on " + BINDING_DEFAULTS, e);
    }

    return l;
  }
Example #7
0
  /**
   * Binds data to this form - that is, handles form submission.
   *
   * @param data data to submit
   * @return a copy of this form filled with the new data
   */
  @SuppressWarnings("unchecked")
  public Form<T> bind(Map<String, String> data, String... allowedFields) {

    DataBinder dataBinder;
    Map<String, String> objectData = data;
    if (rootName == null) {
      dataBinder = new DataBinder(blankInstance());
    } else {
      dataBinder = new DataBinder(blankInstance(), rootName);
      objectData = new HashMap<>();
      for (String key : data.keySet()) {
        if (key.startsWith(rootName + ".")) {
          objectData.put(key.substring(rootName.length() + 1), data.get(key));
        }
      }
    }
    if (allowedFields.length > 0) {
      dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator =
        new SpringValidatorAdapter(play.data.validation.Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    final Map<String, String> objectDataFinal = objectData;
    withRequestLocale(
        () -> {
          dataBinder.bind(new MutablePropertyValues(objectDataFinal));
          return null;
        });
    Set<ConstraintViolation<Object>> validationErrors;
    if (groups != null) {
      validationErrors = validator.validate(dataBinder.getTarget(), groups);
    } else {
      validationErrors = validator.validate(dataBinder.getTarget());
    }

    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
      String field = violation.getPropertyPath().toString();
      FieldError fieldError = result.getFieldError(field);
      if (fieldError == null || !fieldError.isBindingFailure()) {
        try {
          result.rejectValue(
              field,
              violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
              getArgumentsForConstraint(
                  result.getObjectName(), field, violation.getConstraintDescriptor()),
              getMessageForConstraintViolation(violation));
        } catch (NotReadablePropertyException ex) {
          throw new IllegalStateException(
              "JSR-303 validated property '"
                  + field
                  + "' does not have a corresponding accessor for data binding - "
                  + "check your DataBinder's configuration (bean property versus direct field access)",
              ex);
        }
      }
    }

    if (result.hasErrors() || result.getGlobalErrorCount() > 0) {
      Map<String, List<ValidationError>> errors = new HashMap<>();
      for (FieldError error : result.getFieldErrors()) {
        String key = error.getObjectName() + "." + error.getField();
        if (key.startsWith("target.") && rootName == null) {
          key = key.substring(7);
        }
        if (!errors.containsKey(key)) {
          errors.put(key, new ArrayList<>());
        }

        ValidationError validationError;
        if (error.isBindingFailure()) {
          ImmutableList.Builder<String> builder = ImmutableList.builder();
          Optional<Messages> msgs =
              Optional.of(Http.Context.current.get()).map(c -> messagesApi.preferred(c.request()));
          for (String code : error.getCodes()) {
            code = code.replace("typeMismatch", "error.invalid");
            if (!msgs.isPresent() || msgs.get().isDefinedAt(code)) {
              builder.add(code);
            }
          }
          validationError =
              new ValidationError(
                  key, builder.build().reverse(), convertErrorArguments(error.getArguments()));
        } else {
          validationError =
              new ValidationError(
                  key, error.getDefaultMessage(), convertErrorArguments(error.getArguments()));
        }
        errors.get(key).add(validationError);
      }

      List<ValidationError> globalErrors = new ArrayList<>();

      for (ObjectError error : result.getGlobalErrors()) {
        globalErrors.add(
            new ValidationError(
                "", error.getDefaultMessage(), convertErrorArguments(error.getArguments())));
      }

      if (!globalErrors.isEmpty()) {
        errors.put("", globalErrors);
      }

      return new Form(
          rootName, backedType, data, errors, Optional.empty(), groups, messagesApi, formatters);
    } else {
      Object globalError = null;
      if (result.getTarget() != null) {
        try {
          java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
          globalError = v.invoke(result.getTarget());
        } catch (NoSuchMethodException e) {
          // do nothing
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      if (globalError != null) {
        Map<String, List<ValidationError>> errors = new HashMap<>();
        if (globalError instanceof String) {
          errors.put("", new ArrayList<>());
          errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
        } else if (globalError instanceof List) {
          for (ValidationError error : (List<ValidationError>) globalError) {
            List<ValidationError> errorsForKey = errors.get(error.key());
            if (errorsForKey == null) {
              errors.put(error.key(), errorsForKey = new ArrayList<>());
            }
            errorsForKey.add(error);
          }
        } else if (globalError instanceof Map) {
          errors = (Map<String, List<ValidationError>>) globalError;
        }
        return new Form(
            rootName, backedType, data, errors, Optional.empty(), groups, messagesApi, formatters);
      }
      return new Form(
          rootName,
          backedType,
          new HashMap<>(data),
          new HashMap<>(errors),
          Optional.ofNullable((T) result.getTarget()),
          groups,
          messagesApi,
          formatters);
    }
  }
  /**
   * Process and loop until told to stop. A callback_done will stop the loop and will return a
   * result. Otherwise null is returned.
   */
  public Object run() throws CommandException {
    Object result = null;
    boolean shutdown = false;
    boolean closeWhenDone = true;
    Commands.ValueObject valueObject =
        new Commands.ValueObject(); // Working value object so not continually recreated.
    InvokableValueSender valueSender =
        new InvokableValueSender(); // Working valuesender so not continually recreated.
    try {
      boolean doLoop = true;

      /**
       * Note: In the cases below you will see a lot of finally clauses that null variables out.
       * This is because this is a long running loop, and variables declared within blocks are not
       * garbage collected until the method is terminated, so these variables once set would never
       * be GC'd. The nulling at the end of the case makes sure that any of those objects set are
       * now available for garbage collection when necessary.
       */
      while (doLoop && isConnected()) {
        byte cmd = 0;
        try {
          if (LINUX_1_3) socket.setSoTimeout(1000); // Linux 1.3 bug, see comment on LINUX_1_3
          cmd = in.readByte();
          if (LINUX_1_3 && isConnected())
            socket.setSoTimeout(0); // Linux 1.3 bug, see comment on LINUX_1_3
        } catch (InterruptedIOException e) {
          continue; // Timeout, try again
        }
        switch (cmd) {
          case Commands.QUIT_CONNECTION:
            doLoop = false;
            break; // Close this connection

          case Commands.TERMINATE_SERVER:
            doLoop = false;
            shutdown = true; // Shutdown everything
            break;

          case Commands.GET_CLASS:
            String className = in.readUTF();
            Class aClass = null;
            Class superClass = null;
            String superClassName = null;
            boolean added = false;
            try {
              aClass =
                  Class.forName(
                      className); // Turns out using JNI format for array type will work fine.

              added = server.getIdentityID(aClass, valueObject);
              boolean isInterface = aClass.isInterface();
              boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers());
              superClass = aClass.getSuperclass();
              superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$
              out.writeByte(Commands.GET_CLASS_RETURN);
              out.writeInt(valueObject.objectID);
              out.writeBoolean(isInterface);
              out.writeBoolean(isAbstract);
              out.writeUTF(superClassName);
              out.flush();
            } catch (ClassNotFoundException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.GET_CLASS_NOT_FOUND, valueObject);
            } catch (ExceptionInInitializerError e) {
              sendException(e.getException(), valueObject, out);
            } catch (LinkageError e) {
              sendException(e, valueObject, out);
            } catch (Throwable e) {
              // Something bad, did we add a class? If we did remove it from the table.
              if (added) server.removeObject(server.getObject(valueObject.objectID));
              throw e;
            } finally {
              // clear out for GC to work.
              className = null;
              aClass = null;
              superClass = null;
              superClassName = null;
              valueObject.set();
            }
            break;

          case Commands.GET_CLASS_FROM_ID:
            int classID = in.readInt();
            try {
              aClass = (Class) server.getObject(classID);
              boolean isInterface = aClass.isInterface();
              boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers());
              superClass = aClass.getSuperclass();
              superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$
              out.writeByte(Commands.GET_CLASS_ID_RETURN);
              out.writeUTF(aClass.getName());
              out.writeBoolean(isInterface);
              out.writeBoolean(isAbstract);
              out.writeUTF(superClassName);
              out.flush();
            } catch (ClassCastException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
            } finally {
              // clear out for GC to work.
              aClass = null;
              superClass = null;
              superClassName = null;
              valueObject.set();
            }
            break;

          case Commands.GET_OBJECT_DATA:
            int objectID = in.readInt();
            Object anObject = null;
            try {
              anObject = server.getObject(objectID);
              valueObject.setObjectID(objectID, server.getIdentityID(anObject.getClass()));
              Commands.writeValue(out, valueObject, true);
            } catch (ClassCastException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
            } finally {
              anObject = null; // Clear out for GC to work
              valueObject.set();
            }
            break;

          case Commands.RELEASE_OBJECT:
            int id = in.readInt();
            server.removeObject(server.getObject(id));
            break;

          case Commands.NEW_INIT_STRING:
            classID = in.readInt(); // ID Of class to do new upon.
            String initString = in.readUTF(); // The init string.
            Object newValue = null;
            Class theClass = null;
            try {
              theClass = (Class) server.getObject(classID);
              if (theClass == null) {
                // The class wasn't found. So imply ClassNotFound exception.
                throw new ClassNotFoundException();
              }

              InitializationStringParser parser = null;
              try {
                parser = InitializationStringParser.createParser(initString);
                newValue = parser.evaluate();
                boolean primitive = parser.isPrimitive();
                // If expected class is Void.TYPE, that means don't test the type of the result
                // to verify if correct type, just return what it really is.
                if (theClass != Void.TYPE && primitive != theClass.isPrimitive()) {
                  valueObject.set();
                  Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                  continue; // Goto next command.
                }
                if (primitive) {
                  try {
                    // Need to do special tests for compatibility and assignment.
                    sendObject(
                        newValue,
                        classID != Commands.VOID_TYPE
                            ? classID
                            : server.getIdentityID(parser.getExpectedType()),
                        valueObject,
                        out,
                        true); // This will make sure it goes out as the correct primitive type
                  } catch (ClassCastException e) {
                    // The returned type is not of the correct type for what is expected.
                    valueObject.set();
                    Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                    continue; // Goto next command
                  }
                } else {
                  if (newValue != null) {
                    // Test to see if they are compatible. (Null can be assigned to any object,
                    // so that is why it was tested out above).
                    // If expected class is Void.TYPE, that means don't test the type of the result
                    // to verify if correct type, just return what it really is.
                    if (theClass != Void.TYPE && !theClass.isInstance(newValue)) {
                      // The returned type is not of the correct type for what is expected.
                      valueObject.set();
                      Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                      continue; // Goto next command
                    }
                  }
                  sendObject(
                      newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Send out as an object.
                }
              } catch (InitializationStringEvaluationException e) {
                if (e instanceof EvaluationException) {
                  // Want to return the real exception.
                  sendException(e.getOriginalException(), valueObject, out);
                } else {
                  // Couldn't be evaluated, return an error for this.
                  setExceptionIntoValue(e.getOriginalException(), valueObject);
                  Commands.sendErrorCommand(out, Commands.CANNOT_EVALUATE_STRING, valueObject);
                }
              } finally {
                parser = null; // Clear out for GC to work
              }
            } catch (Throwable e) {
              sendException(e, valueObject, out);
            } finally {
              // Clear out for GC to work
              initString = null;
              theClass = null;
              newValue = null;
              valueObject.set();
            }
            break;

          case Commands.INVOKE:
            Object target = null;
            Object[] parms = null;
            Class returnType = null;
            java.lang.reflect.Method aMethod = null;
            try {
              int methodID = in.readInt(); // ID of method to invoke
              aMethod = (java.lang.reflect.Method) server.getObject(methodID); // Method to invoke
              Commands.readValue(in, valueObject);
              target = getInvokableObject(valueObject);
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parms = (Object[]) valueSender.getArray();
              } else {
                // It is all objects or null, so it should be an Object[] or null. If not, then this
                // is an error.
                parms = (Object[]) valueObject.anObject;
              }

              if (!aMethod.isAccessible())
                aMethod.setAccessible(
                    true); // We will allow all to occur. Let access control be handled by IDE and
                           // compiler.
              newValue = aMethod.invoke(target, parms);
              returnType = aMethod.getReturnType();
              if (returnType.isPrimitive()) {
                int returnTypeID = server.getIdentityID(returnType);
                // Need to tell sendObject the correct primitive type.
                sendObject(newValue, returnTypeID, valueObject, out, true);

              } else {
                sendObject(
                    newValue,
                    NOT_A_PRIMITIVE,
                    valueObject,
                    out,
                    true); // Just send the object back. sendObject knows how to iterpret the type
              }
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (java.lang.reflect.InvocationTargetException e) {
              // This is a wrappered exception. Return the wrappered one so it looks like
              // it was the real one. (Sometimes the method being invoked is on a
              // java.lang.reflect.Constructor.newInstance,
              // which in turn is an InvocationTargetException, so we will go until we don't have an
              // InvocationTargetException.
              Throwable t = e;
              do {
                t = ((java.lang.reflect.InvocationTargetException) t).getTargetException();
              } while (t instanceof java.lang.reflect.InvocationTargetException);
              sendException(t, valueObject, out);
            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              // Clear out for GC to work
              valueObject.set();
              parms = null;
              target = null;
              aMethod = null;
              returnType = null;
              newValue = null;
              valueSender.clear();
            }
            break;

          case Commands.INVOKE_WITH_METHOD_PASSED:
            aClass = null;
            String methodName = null;
            Class[] parmTypes = null;
            target = null;
            parms = null;
            returnType = null;
            aMethod = null;

            try {
              Commands.readValue(in, valueObject);
              aClass = (Class) getInvokableObject(valueObject); // The class that has the method.
              methodName = in.readUTF();
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parmTypes = (Class[]) valueSender.getArray();
              } else {
                // It null, so it should be an null. If not, then this is an error.
                parmTypes = null;
              }
              aMethod = aClass.getMethod(methodName, parmTypes);

              // Now we get the info for the invocation of the method and execute it.
              Commands.readValue(in, valueObject);
              target = getInvokableObject(valueObject);
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parms = (Object[]) valueSender.getArray();
              } else {
                // It is all objects or null, so it should be an Object[] or null. If not, then this
                // is an error.
                parms = (Object[]) valueObject.anObject;
              }

              if (!aMethod.isAccessible())
                aMethod.setAccessible(
                    true); // We will allow all to occur. Let access control be handled by IDE and
                           // compiler.
              newValue = aMethod.invoke(target, parms);
              returnType = aMethod.getReturnType();
              if (returnType.isPrimitive()) {
                int returnTypeID = server.getIdentityID(returnType);
                // Need to tell sendObject the correct primitive type.
                sendObject(newValue, returnTypeID, valueObject, out, true);

              } else {
                sendObject(
                    newValue,
                    NOT_A_PRIMITIVE,
                    valueObject,
                    out,
                    true); // Just send the object back. sendObject knows how to iterpret the type
              }
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (java.lang.reflect.InvocationTargetException e) {
              // This is a wrappered exception. Return the wrappered one so it looks like
              // it was the real one. (Sometimes the method being invoked is on a
              // java.lang.reflect.Constructor.newInstance,
              // which in turn is an InvocationTargetException, so we will go until we don't have an
              // InvocationTargetException.
              Throwable t = e;
              do {
                t = ((java.lang.reflect.InvocationTargetException) t).getTargetException();
              } while (t instanceof java.lang.reflect.InvocationTargetException);
              sendException(t, valueObject, out);

            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              aClass = null;
              methodName = null;
              parmTypes = null;
              // Clear out for GC to work
              valueObject.set();
              parms = null;
              target = null;
              aMethod = null;
              returnType = null;
              newValue = null;
              valueSender.clear();
            }
            break;

          case Commands.GET_ARRAY_CONTENTS:
            try {
              target = server.getObject(in.readInt()); // Array to get the ids for.
              valueObject.setArrayIDS(
                  new ArrayContentsRetriever(target),
                  Array.getLength(target),
                  Commands.OBJECT_CLASS);
              Commands.writeValue(out, valueObject, true); // Write it back as a value command.
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              target = null;
              valueObject.set();
            }
            break;

          case Commands.CALLBACK_DONE:
            try {
              if (connectionThread != null) {
                valueObject.set();
                Commands.sendErrorCommand(out, Commands.UNKNOWN_COMMAND_SENT, valueObject);
              } else {
                try {
                  Commands.readBackValue(in, valueObject, Commands.NO_TYPE_CHECK);
                  if (valueObject.type == Commands.ARRAY_IDS) {
                    // It is an array containing IDs, as it normally would be.
                    valueSender.initialize(valueObject);
                    Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                    result = valueSender.getArray();
                  } else {
                    result = getInvokableObject(valueObject);
                  }
                  doLoop = false; // We need to terminate and return result
                  closeWhenDone = false; // Don't close, we will continue.
                } catch (CommandErrorException e) {
                  // There was an command error on the other side. This means
                  // connection still good, but don't continue the callback processing.
                  doLoop = false; // We need to terminate and return result
                  closeWhenDone = false; // Don't close, we will continue.
                  throw e; // Let it go on out.
                }
              }
            } finally {
              valueObject.set();
              valueSender.clear();
            }
            break;

          case Commands.ERROR:
            try {
              // Got an error command. Don't know what to do but read the
              // value and simply print it out.
              Commands.readValue(in, valueObject);
              result = getInvokableObject(valueObject);
              System.out.println("Error sent to server: Result=" + result); // $NON-NLS-1$
            } finally {
              valueObject.set();
            }
            break;

          case Commands.EXPRESSION_TREE_COMMAND:
            try {
              processExpressionCommand(valueObject, valueSender);
            } finally {
              valueObject.set();
              valueSender.clear();
            }
            break;

          default:
            // Unknown command. We don't know how long it is, so we need to shut the connection
            // down.
            System.err.println("Error: Invalid cmd send to server: Cmd=" + cmd); // $NON-NLS-1$
            doLoop = false;
            closeWhenDone = true;
            break;
        }
      }
    } catch (EOFException e) {
      // This is ok. It means that the connection on the other side was terminated.
      // So just accept this and go down.
    } catch (CommandException e) {
      throw e;
    } catch (SocketException e) {
      if (socket != null)
        throw new UnexpectedExceptionCommandException(
            false, e); // socket null means a valid close request
    } catch (Throwable e) {
      e.printStackTrace();
    } finally {
      if (closeWhenDone) {
        try {
          for (Iterator itr = expressionProcessors.values().iterator(); itr.hasNext(); ) {
            ExpressionProcesserController exp = (ExpressionProcesserController) itr.next();
            exp.close();
          }
        } finally {
          expressionProcessors.clear();
        }

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

    if (closeWhenDone && connectionThread != null) server.removeConnectionThread(connectionThread);
    if (shutdown) server.requestShutdown();

    return result;
  }
Example #9
0
  /** @param arg */
  public static void main(String arg[]) {
    TestApp af = new TestApp();

    SourceImage sImg = null;

    int imagesPerRow = 0;
    int imagesPerCol = 0;

    int imgMin = 65536;
    int imgMax = 0;

    boolean signed = false;
    boolean inverted = false;
    boolean hasPad = false;
    int padValue = 0;

    if (arg.length == 6) {
      // do it with raw file
      int w = 0;
      int h = 0;
      int d = 0;
      try {
        w = Integer.valueOf(arg[1]).intValue();
        h = Integer.valueOf(arg[2]).intValue();
        d = Integer.valueOf(arg[3]).intValue();
        imagesPerRow = Integer.valueOf(arg[4]).intValue();
        imagesPerCol = Integer.valueOf(arg[5]).intValue();
      } catch (Exception e) {
        System.err.println(e);
        System.exit(0);
      }

      try {
        FileInputStream i = new FileInputStream(arg[0]);
        sImg = new SourceImage(i, w, h, d);
      } catch (Exception e) {
        System.err.println(e);
        System.exit(0);
      }
    } else {
      // do it with DICOM file

      if (arg.length > 2) {
        try {
          imagesPerRow = Integer.valueOf(arg[1]).intValue();
          imagesPerCol = Integer.valueOf(arg[2]).intValue();
        } catch (Exception e) {
          System.err.println(e);
          e.printStackTrace(System.err);
          System.exit(0);
        }
      } else {
        imagesPerRow = 1;
        imagesPerCol = 1;
      }

      try {
        DicomInputStream i = new DicomInputStream(new FileInputStream(arg[0]));
        sImg = new SourceImage(i);
      } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace(System.err);
        System.exit(0);
      }
    }

    try {
      // com.apple.cocoa.application.NSMenu.setMenuBarVisible(false);							// Won't compile on
      // other platforms
      // Class classToUse =
      // ClassLoader.getSystemClassLoader().loadClass("com.apple.cocoa.application.NSMenu");	//
      // Needs "/System/Library/Java" in classpath
      Class classToUse =
          new java.net.URLClassLoader(new java.net.URL[] {new File("/System/Library/Java").toURL()})
              .loadClass("com.apple.cocoa.application.NSMenu");
      Class[] parameterTypes = {Boolean.TYPE};
      java.lang.reflect.Method methodToUse =
          classToUse.getDeclaredMethod("setMenuBarVisible", parameterTypes);
      Object[] args = {Boolean.FALSE};
      methodToUse.invoke(null /*since static*/, args);
    } catch (Exception e) { // ClassNotFoundException,NoSuchMethodException,IllegalAccessException
      e.printStackTrace(System.err);
    }

    java.awt.Dimension d = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    int frameWidth = (int) d.getWidth();
    int frameHeight = (int) d.getHeight();
    System.err.println("frameWidth=" + frameWidth);
    System.err.println("frameHeight=" + frameHeight);
    af.setUndecorated(true);
    af.setLocation(0, 0);
    af.setSize(frameWidth, frameHeight);

    JPanel multiPanel = new JPanel();
    multiPanel.setLayout(new GridLayout(imagesPerCol, imagesPerRow));
    multiPanel.setBackground(Color.black);

    SingleImagePanel imagePanel[] = new SingleImagePanel[imagesPerRow * imagesPerCol];

    int singleWidth = frameWidth / imagesPerRow;
    int singleHeight = frameHeight / imagesPerCol;
    System.err.println("singleWidth=" + singleWidth);
    System.err.println("singleHeight=" + singleHeight);

    for (int x = 0; x < imagesPerCol; ++x) {
      for (int y = 0; y < imagesPerRow; ++y) {
        SingleImagePanel ip = new SingleImagePanel(sImg);
        // ip.setPreferredSize(new Dimension(img.getWidth(),img.getHeight()));
        // ip.setPreferredSize(new Dimension(sImg.getWidth(),sImg.getHeight()));
        ip.setPreferredSize(new Dimension(singleWidth, singleHeight));
        multiPanel.add(ip);
        imagePanel[x * imagesPerRow + y] = ip;
      }
    }

    // multiPanel.setSize(img.getWidth()*imagesPerRow,img.getHeight()*imagesPerRow);

    // JScrollPane scrollPane = new JScrollPane(multiPanel);

    Container content = af.getContentPane();
    content.setLayout(new GridLayout(1, 1));
    // content.add(scrollPane);
    content.add(multiPanel);

    af.pack();
    af.setVisible(true);
  }
  /**
   * 执行反射
   *
   * @param valueObject
   * @param methordName
   * @param type
   * @param defaultValue
   * @return
   */
  private S_FrameWork_Query_OperationValueObject invokeMethord(
      S_FrameWork_Query_OperationValueObject valueObject,
      String methordName,
      String type,
      String defaultValue) {

    // 映射
    String[] paramStr;
    Integer[] paramI;
    Timestamp[] paramDate;
    Float[] paramfl;
    Date[] paramSqlDate;
    java.lang.reflect.Method m;
    Object b;
    DefaultValue dv = new DefaultValue();
    HttpServletRequest request = super.getHttpServletRequest();
    dv.setRequest(request);
    dv.setObjectManager((ApplicationUSOM) getUSOM());

    try {

      // 1.判断数据类型
      // 2.设置默认值
      // 3.默认值有三种:系统信息,用户信息,request信息,session信息
      if (type.equalsIgnoreCase("String")) {

        paramStr = new String[] {dv.setDefault(defaultValue)}; // 字符串
        m =
            (S_FrameWork_Query_OperationValueObject.class)
                .getMethod(methordName, new Class[] {String.class});
        b = m.invoke(valueObject, paramStr);
        return valueObject;

      } else if (type.equalsIgnoreCase("float")) {

        paramfl = new Float[] {Float.valueOf(dv.setDefault(defaultValue))}; // 字符串
        m =
            (S_FrameWork_Query_OperationValueObject.class)
                .getMethod(methordName, new Class[] {Float.class});
        b = m.invoke(valueObject, paramfl);
        return valueObject;

      } else if (type.equalsIgnoreCase("integer")) {

        paramI = new Integer[] {new Integer(dv.setDefault(defaultValue))}; // 整型
        m =
            (S_FrameWork_Query_OperationValueObject.class)
                .getMethod(methordName, new Class[] {int.class});
        b = m.invoke(valueObject, paramI);
        return valueObject;

      } else if (type.equalsIgnoreCase("datetime") || type.equalsIgnoreCase("date")) {

        try {
          paramDate = new Timestamp[] {formatToTimestamp(dv.setDefault(defaultValue))}; // 日期
          m =
              (S_FrameWork_Query_OperationValueObject.class)
                  .getMethod(methordName, new Class[] {Timestamp.class});
          b = m.invoke(valueObject, paramDate);
          return valueObject;
        } catch (Exception e) {
          try {
            paramSqlDate = new Date[] {formatToSQLDATE(dv.setDefault(defaultValue))}; // 日期
            m =
                (S_FrameWork_Query_OperationValueObject.class)
                    .getMethod(methordName, new Class[] {java.sql.Date.class});
            b = m.invoke(valueObject, paramSqlDate);
            return valueObject;
          } catch (Exception e1) {
            e1.printStackTrace();
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return valueObject;
  }
Example #11
0
  public static void doIt(Config config) throws java.io.IOException, Schema2BeansException {
    normalizeConfig(config);

    calculateNewestSourceTime(config);

    boolean needToWriteMetaDD = processMetaDD(config);

    //  The class that build the DTD object graph
    TreeBuilder tree = new TreeBuilder(config);

    //  The file parser calling back the handler
    SchemaParser parser = null;
    boolean tryAgain;
    int schemaType = config.getSchemaTypeNum();
    SchemaParseException lastException = null;
    do {
      tryAgain = false;
      if (schemaType == Config.XML_SCHEMA) {
        XMLSchemaParser xmlSchemaParser = new XMLSchemaParser(config, tree);
        if (config.getInputURI() != null) xmlSchemaParser.setInputURI(config.getInputURI());
        parser = xmlSchemaParser;
      } else {
        parser = new DocDefParser(config, tree);
      }
      readBeanGraphs(config);

      try {
        //  parse the DTD, building the object graph
        parser.process();
      } catch (SchemaParseException e) {
        if (schemaType == Config.DTD) {
          // Retry as XML Schema
          tryAgain = true;
          schemaType = Config.XML_SCHEMA;
        } else {
          if (lastException == null) throw e;
          else throw lastException;
        }
        lastException = e;
      }
    } while (tryAgain);
    config.setSchemaTypeNum(schemaType);

    // Build the beans from the graph, and code generate them out to disk.
    BeanBuilder builder = new BeanBuilder(tree, config, config.getCodeGeneratorFactory());
    builder.process();

    if (needToWriteMetaDD) {
      try {
        config.messageOut.println("Writing metaDD XML file"); // NOI18N
        FileOutputStream mddOut = new FileOutputStream(config.getMddFile());
        config.getMetaDD().write(mddOut);
        mddOut.close();
      } catch (IOException e) {
        config.messageOut.println("Failed to write the mdd file: " + e.getMessage()); // NOI18N
        throw e;
      }
    }

    if (config.isDoCompile()
        && config.getOutputStreamProvider() instanceof DefaultOutputStreamProvider) {
      DefaultOutputStreamProvider out =
          (DefaultOutputStreamProvider) config.getOutputStreamProvider();
      String[] javacArgs = new String[out.getGeneratedFiles().size()];
      int javaFileCount = 0;
      for (Iterator it = out.getGeneratedFiles().iterator(); it.hasNext(); ) {
        javacArgs[javaFileCount] = (String) it.next();
        ++javaFileCount;
      }

      if (javaFileCount == 0) {
        if (!config.isQuiet()) config.messageOut.println(Common.getMessage("MSG_NothingToCompile"));
      } else {
        if (!config.isQuiet()) config.messageOut.println(Common.getMessage("MSG_Compiling"));
        try {
          Class javacClass = Class.forName("com.sun.tools.javac.Main");
          java.lang.reflect.Method compileMethod =
              javacClass.getDeclaredMethod(
                  "compile", new Class[] {String[].class, PrintWriter.class});
          // com.sun.tools.javac.Main.compile(javacArgs, pw);
          PrintWriter pw = new PrintWriter(config.messageOut, true);
          Object result = compileMethod.invoke(null, new Object[] {javacArgs, pw});
          pw.flush();
          int compileExitCode = 0;
          if (result instanceof Integer) compileExitCode = ((Integer) result).intValue();
          if (compileExitCode != 0)
            throw new RuntimeException(
                "Compile errors: javac had an exit code of " + compileExitCode);
        } catch (java.lang.Exception e) {
          // Maybe it's just a missing $JRE/tools.jar from
          // the CLASSPATH.
          // config.messageOut.println(Common.getMessage("MSG_UnableToCompile"));
          // config.messageOut.println(e.getClass().getName()+": "+e.getMessage());	// NOI18N
          // e.printStackTrace();
          if (e instanceof IOException) throw (IOException) e;
          if (e instanceof Schema2BeansException) throw (Schema2BeansException) e;
          throw new Schema2BeansNestedException(Common.getMessage("MSG_UnableToCompile"), e);
        }
      }
    }
  }
Example #12
0
  /**
   * Binds data to this form - that is, handles form submission.
   *
   * @param data data to submit
   * @return a copy of this form filled with the new data
   */
  public Form<T> bind(Map<String, String> data, String... allowedFields) {

    DataBinder dataBinder = null;
    Map<String, String> objectData = data;
    if (rootName == null) {
      dataBinder = new DataBinder(blankInstance());
    } else {
      dataBinder = new DataBinder(blankInstance(), rootName);
      objectData = new HashMap<String, String>();
      for (String key : data.keySet()) {
        if (key.startsWith(rootName + ".")) {
          objectData.put(key.substring(rootName.length() + 1), data.get(key));
        }
      }
    }
    if (allowedFields.length > 0) {
      dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator =
        new SpringValidatorAdapter(play.data.validation.Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));
    Set<ConstraintViolation<Object>> validationErrors;
    if (groups != null) {
      validationErrors = validator.validate(dataBinder.getTarget(), groups);
    } else {
      validationErrors = validator.validate(dataBinder.getTarget());
    }

    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
      String field = violation.getPropertyPath().toString();
      FieldError fieldError = result.getFieldError(field);
      if (fieldError == null || !fieldError.isBindingFailure()) {
        try {
          result.rejectValue(
              field,
              violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
              getArgumentsForConstraint(
                  result.getObjectName(), field, violation.getConstraintDescriptor()),
              violation.getMessage());
        } catch (NotReadablePropertyException ex) {
          throw new IllegalStateException(
              "JSR-303 validated property '"
                  + field
                  + "' does not have a corresponding accessor for data binding - "
                  + "check your DataBinder's configuration (bean property versus direct field access)",
              ex);
        }
      }
    }

    if (result.hasErrors()) {
      Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
      for (FieldError error : result.getFieldErrors()) {
        String key = error.getObjectName() + "." + error.getField();
        if (key.startsWith("target.") && rootName == null) {
          key = key.substring(7);
        }
        List<Object> arguments = new ArrayList<Object>();
        for (Object arg : error.getArguments()) {
          if (!(arg
              instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
            arguments.add(arg);
          }
        }
        if (!errors.containsKey(key)) {
          errors.put(key, new ArrayList<ValidationError>());
        }
        errors
            .get(key)
            .add(
                new ValidationError(
                    key,
                    error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(),
                    arguments));
      }
      return new Form(rootName, backedType, data, errors, None(), groups);
    } else {
      Object globalError = null;
      if (result.getTarget() != null) {
        try {
          java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
          globalError = v.invoke(result.getTarget());
        } catch (NoSuchMethodException e) {
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      if (globalError != null) {
        Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
        if (globalError instanceof String) {
          errors.put("", new ArrayList<ValidationError>());
          errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
        } else if (globalError instanceof List) {
          errors.put("", (List<ValidationError>) globalError);
        } else if (globalError instanceof Map) {
          errors = (Map<String, List<ValidationError>>) globalError;
        }
        return new Form(rootName, backedType, data, errors, None(), groups);
      }
      return new Form(
          rootName,
          backedType,
          new HashMap<String, String>(data),
          new HashMap<String, List<ValidationError>>(errors),
          Some((T) result.getTarget()),
          groups);
    }
  }
Example #13
0
  public static void main(String args[])
      throws DbException, TransactionAbortedException, IOException {
    // convert a file
    if (args[0].equals("convert")) {
      try {
        if (args.length == 3) {
          HeapFileEncoder.convert(
              new File(args[1]),
              new File(args[1].replaceAll(".txt", ".dat")),
              BufferPool.PAGE_SIZE,
              Integer.parseInt(args[2]));
        } else if (args.length == 4) {
          ArrayList<Type> ts = new ArrayList<Type>();
          String[] typeStringAr = args[3].split(",");
          for (String s : typeStringAr) {
            if (s.toLowerCase().equals("int")) ts.add(Type.INT_TYPE);
            else if (s.toLowerCase().equals("string")) ts.add(Type.STRING_TYPE);
            else {
              System.out.println("Unknown type " + s);
              return;
            }
          }
          HeapFileEncoder.convert(
              new File(args[1]),
              new File(args[1].replaceAll(".txt", ".dat")),
              BufferPool.PAGE_SIZE,
              Integer.parseInt(args[2]),
              ts.toArray(new Type[0]));

        } else {
          System.out.println("Unexpected number of arguments to convert ");
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else if (args[0].equals("print")) {
      File tableFile = new File(args[1]);
      int columns = Integer.parseInt(args[2]);
      DbFile table = Utility.openHeapFile(columns, tableFile);
      TransactionId tid = new TransactionId();
      DbFileIterator it = table.iterator(tid);

      if (null == it) {
        System.out.println(
            "Error: method HeapFile.iterator(TransactionId tid) not yet implemented!");
      } else {
        it.open();
        while (it.hasNext()) {
          Tuple t = it.next();
          System.out.println(t);
        }
        it.close();
      }
    } else if (args[0].equals("parser")) {
      // Strip the first argument and call the parser
      String[] newargs = new String[args.length - 1];
      for (int i = 1; i < args.length; ++i) {
        newargs[i - 1] = args[i];
      }

      try {
        // dynamically load Parser -- if it doesn't exist, print error message
        Class<?> c = Class.forName("simpledb.Parser");
        Class<?> s = String[].class;

        java.lang.reflect.Method m = c.getMethod("main", s);
        m.invoke(null, (java.lang.Object) newargs);
      } catch (ClassNotFoundException cne) {
        System.out.println(
            "Class Parser not found -- perhaps you are trying to run the parser as a part of lab1?");
      } catch (Exception e) {
        System.out.println("Error in parser.");
        e.printStackTrace();
      }

    } else {
      System.err.println("Unknown command: " + args[0]);
      System.exit(1);
    }
  }