Exemplo n.º 1
1
  public AppletControl(String u, int w, int h, String user, String p) {

    PARAMETERS.put("RemoteHost", u.split("//")[1].split(":")[0]);
    PARAMETERS.put("RemotePort", u.split(":")[2].split("/")[0]);
    System.out.println(PARAMETERS.toString());
    this.url = u;
    URL[] url = new URL[1];
    try {

      url[0] = new URL(u);
      URLClassLoader load = new URLClassLoader(url);
      try {
        try {
          app = (Applet) load.loadClass("aplug").newInstance();
          app.setSize(w, h);
          app.setStub(this);
          app.setVisible(true);
        } catch (InstantiationException ex) {
          ex.printStackTrace();
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        }
      } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
      }
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 2
0
  private static void addRSPack(boolean refreash) {
    File rspack = new File(getConfigFolder(), "/resources");
    if (!rspack.exists()) return;

    if (!Arrays.asList(rspack.list()).contains("pack.mcmeta")) {
      try {
        JsonWriter writer = new JsonWriter(new FileWriter(new File(rspack, "pack.mcmeta")));
        writer.beginObject();
        writer.name("pack");
        writer.beginObject();
        writer.name("pack_format").value(1);
        writer.name("description").value("Draconic Evolution GUI Images");
        writer.endObject();
        writer.endObject();
        writer.close();
      } catch (IOException e) {
        LogHelper.error("Error creating pack.mcmeta");
        e.printStackTrace();
      }
    }

    Field f =
        ReflectionHelper.findField(Minecraft.class, "defaultResourcePacks", "field_110449_ao");
    f.setAccessible(true);
    try {
      List defaultResourcePacks = (List) f.get(Minecraft.getMinecraft());
      defaultResourcePacks.add(new FolderResourcePack(rspack));

      f.set(Minecraft.getMinecraft(), defaultResourcePacks);
      LogHelper.info("RS Added");
      if (refreash) Minecraft.getMinecraft().refreshResources();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 3
0
  /*
   * launch process config input: className and args
   */
  public void launchProcessConfig(String className, String[] args)
      throws SecurityException, NoSuchMethodException {

    try {
      Class<?> processClass = Class.forName(className);
      // System.out.print("processClass is " + processClass.toString());
      MigratableProcess process;
      process =
          (MigratableProcess)
              processClass.getConstructor(String[].class).newInstance((Object) args);
      //			process = (MigratableProcess) processClass.newInstance();
      System.out.println("MP is " + process.toString());
      processList.add(process);

    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } // TestProcess test = new TestProcess();
    catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 4
0
  public void setEntity(java.lang.Object ent) {
    Method[] methods = ent.getClass().getDeclaredMethods();
    box.removeAll();
    for (Method m : methods) {
      if (m.getName().toLowerCase().startsWith("get")) {
        String attName = m.getName().substring(3);
        Object result;
        try {
          result = m.invoke(ent, new Object[] {});
          String value = "null";
          if (result != null) value = result.toString();
          JPanel attPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
          attPane.add(new JLabel(attName + " : " + m.getReturnType().getName() + " = " + value));
          box.add(attPane);
        } catch (IllegalArgumentException e) {

          e.printStackTrace();
        } catch (IllegalAccessException e) {

          e.printStackTrace();
        } catch (InvocationTargetException e) {

          e.printStackTrace();
        }
      }
    }
  }
Exemplo n.º 5
0
 /**
  * Insert the source code details, if available.
  *
  * @param ped The given program element.
  */
 public void addSourcePosition(ProgramElementDoc ped, int indent) {
   if (!addSrcInfo) return;
   if (JDiff.javaVersion.startsWith("1.1")
       || JDiff.javaVersion.startsWith("1.2")
       || JDiff.javaVersion.startsWith("1.3")) {
     return; // position() only appeared in J2SE1.4
   }
   try {
     // Could cache the method for improved performance
     Class c = ProgramElementDoc.class;
     Method m = c.getMethod("position", null);
     Object sp = m.invoke(ped, null);
     if (sp != null) {
       for (int i = 0; i < indent; i++) outputFile.print(" ");
       outputFile.println("src=\"" + sp + "\"");
     }
   } catch (NoSuchMethodException e2) {
     System.err.println("Error: method \"position\" not found");
     e2.printStackTrace();
   } catch (IllegalAccessException e4) {
     System.err.println("Error: class not permitted to be instantiated");
     e4.printStackTrace();
   } catch (InvocationTargetException e5) {
     System.err.println("Error: method \"position\" could not be invoked");
     e5.printStackTrace();
   } catch (Exception e6) {
     System.err.println("Error: ");
     e6.printStackTrace();
   }
 }
  /**
   * Creates the brain and launches if it is an agent. The brain class is given as a String. The
   * name argument is used to instantiate the name of the corresponding agent. If the gui flag is
   * true, a bean is created and associated to this agent.
   */
  public void makeBrain(String className, String name, boolean gui, String behaviorFileName) {
    try {
      Class c;
      // c = Class.forName(className);
      c = madkit.kernel.Utils.loadClass(className);
      myBrain = (Brain) c.newInstance();
      myBrain.setBody(this);
      if (myBrain instanceof AbstractAgent) {
        String n = name;
        if (n == null) {
          n = getLabel();
        }
        if (n == null) {
          n = getID();
        }
        if (behaviorFileName != null) setBehaviorFileName(behaviorFileName);
        getStructure().getAgent().doLaunchAgent((AbstractAgent) myBrain, n, gui);
      }

    } catch (ClassNotFoundException ev) {
      System.err.println("Class not found :" + className + " " + ev);
      ev.printStackTrace();
    } catch (InstantiationException e) {
      System.err.println("Can't instanciate ! " + className + " " + e);
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      System.err.println("illegal access! " + className + " " + e);
      e.printStackTrace();
    }
  }
Exemplo n.º 7
0
  private static <T extends Object> T getMultiConfig(Class<T> c, String path) {
    File file = new File(path);
    try {
      T t = c.newInstance();

      File[] files = file.listFiles();

      if (files == null) return null;

      for (File f : files) {
        if (f.isDirectory()) continue;
        if (!f.getName().toLowerCase().endsWith(".xml")) continue;

        InputStream input = new FileInputStream(f);

        XStream stream = new XStream(new AnnotationJavaReflectionProvider());
        stream.alias("root", c);
        stream.processAnnotations(c);
        t = (T) stream.fromXML(input, t);
      }
      return t;
    } catch (FileNotFoundException e) {
      return null;
    } catch (InstantiationException e) {
      e.printStackTrace();
      return null;
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      return null;
    }
  }
Exemplo n.º 8
0
  /**
   * forward an execute request to a helper instance associated with the rule
   *
   * @param recipient the recipient of the method from which execution of this rule was triggered or
   *     null if it was a static method
   * @param args the arguments of the method from which execution of this rule was triggered
   */
  private void execute(Object recipient, Object[] args) throws ExecuteException {
    // type check and createHelperAdapter the rule now if it has not already been done

    if (ensureTypeCheckedCompiled()) {

      // create a helper and get it to execute the rule
      // eventually we will create a subclass of helper for each rule and createHelperAdapter
      // an implementation of execute from the rule source. for now we create a generic
      // helper and call the generic execute method which interprets the rule
      HelperAdapter helper;
      try {
        Constructor constructor = helperImplementationClass.getConstructor(Rule.class);
        helper = (HelperAdapter) constructor.newInstance(this);
        // helper = (RuleHelper)helperClass.newInstance();
        // helper.setRule(this);
        helper.execute(recipient, args);
      } catch (NoSuchMethodException e) {
        // should not happen!!!
        System.out.println(
            "cannot find constructor "
                + helperImplementationClass.getCanonicalName()
                + "(Rule) for helper class");
        e.printStackTrace(System.out);
        return;
      } catch (InvocationTargetException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InstantiationException e) {
        // should not happen
        System.out.println(
            "cannot create instance of " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (IllegalAccessException e) {
        // should not happen
        System.out.println("cannot access " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (ClassCastException e) {
        // should not happen
        System.out.println("cast exception " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (EarlyReturnException e) {
        throw e;
      } catch (ThrowException e) {
        throw e;
      } catch (ExecuteException e) {
        System.out.println(getName() + " : " + e);
        throw e;
      } catch (Throwable throwable) {
        System.out.println(getName() + " : " + throwable);
        throw new ExecuteException(getName() + "  : caught " + throwable, throwable);
      }
    }
  }
Exemplo n.º 9
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    HttpSession session = request.getSession();
    request.setCharacterEncoding("UTF-8");

    BufferedInputStream fileIn = new BufferedInputStream(request.getInputStream());
    String fn = request.getParameter("fileName");
    byte[] buf = new byte[1024];
    File file = new File("/var/www/uploadres/" + session.getAttribute("username") + fn);
    BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file));
    while (true) {
      int bytesIn = fileIn.read(buf, 0, 1024);
      if (bytesIn == -1) break;
      else fileOut.write(buf, 0, bytesIn);
    }

    fileOut.flush();
    fileOut.close();
    System.out.println(file.getAbsolutePath());

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      try {
        Connection conn = DriverManager.getConnection(url, user, pwd);
        Statement stmt = conn.createStatement();
        String sql =
            "UPDATE Users SET photo = '"
                + file.getName()
                + "' WHERE username='******'";
        stmt.execute(sql);
        //				PreparedStatement pstmt = conn.prepareStatement("UPDATE Users SET photo = ? WHERE
        // username='******'");
        //				InputStream inp = new BufferedInputStream(new FileInputStream(file));
        //				pstmt.setBinaryStream(1, inp, (int)file.length());
        //				pstmt.executeUpdate();
        System.out.println("OK");
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 10
0
  public void processAction(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    System.out.println("processing test driver request ... ");

    processParams(request);
    boolean status = false;
    System.out.println("tc:" + tc);

    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    out.println("TestCase: " + tc);

    if (tc != null) {

      try {
        Class<?> c = getClass();
        Object t = this;

        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
          String mname = m.getName();
          if (!mname.equals(tc.trim())) {
            continue;
          }

          System.out.println("Invoking : " + mname);
          try {
            m.setAccessible(true);
            Object o = m.invoke(t);
            System.out.println("Returned => " + (Boolean) o);
            status = new Boolean((Boolean) o).booleanValue();
            // Handle any methods thrown by method to be invoked
          } catch (InvocationTargetException x) {
            Throwable cause = x.getCause();

            System.err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
          } catch (IllegalAccessException x) {
            x.printStackTrace();
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      if (status) {
        out.println(tc + ":pass");
      } else {
        out.println(tc + ":fail");
      }
    }
  }
Exemplo n.º 11
0
  /**
   * Updates a resource on the ckan server.
   *
   * @param resource ckan resource object
   * @return the updated resource
   * @throws JackanException
   */
  public synchronized CkanResource updateResource(CkanResource resource, Boolean checkConsistency) {

    if (ckanToken == null) {
      throw new JackanException(
          "Tried to update resource" + resource.getName() + ", but ckan token was not set!");
    }
    // check consistance with original version of the to be updated resource
    if (checkConsistency) {
      CkanResource originalResource = getResource(resource.getId());

      for (Field f : originalResource.getClass().getDeclaredFields()) {
        f.setAccessible(true);
        String fieldName;
        try {
          if ((f.get(originalResource) != null)
              && (f.get(resource) == null)
              && (!f.getName().equals("created"))) {
            fieldName = f.getName();
            //						if(!fieldName.equals("created")){
            f.set(resource, f.get(originalResource));
            System.out.println("Not a null: " + fieldName + " Value: ");
            //						//};
            //								System.out.println("Not a null: "+fieldName+ " Value: ");
          }
        } catch (IllegalArgumentException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
    // System.out.println("After consistance checking resource is consist of:
    // "+resource.toString());

    ObjectMapper objectMapper = CkanClient.getObjectMapper();
    String json = null;
    try {
      json = objectMapper.writeValueAsString(resource);
    } catch (IOException e) {
      throw new JackanException("Couldn't serialize the provided CkanResourceMinimized!", e);
    }

    return postHttp(
            ResourceResponse.class,
            "/api/3/action/resource_update",
            json,
            ContentType.APPLICATION_JSON)
        .result;
  }
  @Nullable
  static ClassLoader createPluginClassLoader(
      @NotNull File[] classPath,
      @NotNull ClassLoader[] parentLoaders,
      @NotNull IdeaPluginDescriptor pluginDescriptor) {

    if (pluginDescriptor.getUseIdeaClassLoader()) {
      try {
        final ClassLoader loader = PluginManagerCore.class.getClassLoader();
        final Method addUrlMethod = getAddUrlMethod(loader);

        for (File aClassPath : classPath) {
          final File file = aClassPath.getCanonicalFile();
          addUrlMethod.invoke(loader, file.toURI().toURL());
        }

        return loader;
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }

    PluginId pluginId = pluginDescriptor.getPluginId();
    File pluginRoot = pluginDescriptor.getPath();

    // if (classPath.length == 0) return null;
    if (isUnitTestMode()) return null;
    try {
      final List<URL> urls = new ArrayList<URL>(classPath.length);
      for (File aClassPath : classPath) {
        final File file =
            aClassPath
                .getCanonicalFile(); // it is critical not to have "." and ".." in classpath
                                     // elements
        urls.add(file.toURI().toURL());
      }
      return new PluginClassLoader(
          urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Exemplo n.º 13
0
 /**
  * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly
  * duplicates tryMethod in JGEngine.
  *
  * @return null means method does not exist or returned null/void
  */
 static Object tryMethod(Object o, String name, Object[] args) {
   try {
     Method met = JREEngine.getMethod(o.getClass(), name, args);
     if (met == null) return null;
     return met.invoke(o, args);
   } catch (InvocationTargetException ex) {
     Throwable ex_t = ex.getTargetException();
     ex_t.printStackTrace();
     return null;
   } catch (IllegalAccessException ex) {
     System.err.println("Unexpected exception:");
     ex.printStackTrace();
     return null;
   }
 }
Exemplo n.º 14
0
 public static Integer getProcessID(Process p) {
   try {
     Field f = p.getClass().getDeclaredField("pid");
     f.setAccessible(true);
     Integer s = (Integer) f.get(p);
     return s;
   } catch (NoSuchFieldException e) {
     e.printStackTrace();
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
   return null;
 }
Exemplo n.º 15
0
 // Lookup the value corresponding to a key found in catalog.getKeys().
 // Here we assume that the catalog returns a non-inherited value for
 // these keys. FIXME: Not true. Better see whether handleGetObject is
 // public - it is in ListResourceBundle and PropertyResourceBundle.
 private Object lookup(String key) {
   Object value = null;
   if (lookupMethod != null) {
     try {
       value = lookupMethod.invoke(catalog, new Object[] {key});
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       e.getTargetException().printStackTrace();
     }
   } else {
     try {
       value = catalog.getObject(key);
     } catch (MissingResourceException e) {
     }
   }
   return value;
 }
Exemplo n.º 16
0
 public List<Object> readExcel(Workbook wb, Class clz, int readLine, int tailLine) {
   Sheet sheet = wb.getSheetAt(0); // 取第一张表
   List<Object> objs = null;
   try {
     Row row = sheet.getRow(readLine); // 开始行,主题栏
     objs = new ArrayList<Object>();
     Map<Integer, String> maps = getHeaderMap(row, clz); // 设定对应的字段顺序与方法名
     if (maps == null || maps.size() <= 0)
       throw new RuntimeException("要读取的Excel的格式不正确,检查是否设定了合适的行"); // 与order顺序不符
     for (int i = readLine + 1; i <= sheet.getLastRowNum() - tailLine; i++) { // 取数据
       row = sheet.getRow(i);
       Object obj = clz.newInstance(); //   调用无参结构
       for (Cell c : row) {
         int ci = c.getColumnIndex();
         String mn = maps.get(ci).substring(3); // 消除get
         mn = mn.substring(0, 1).toLowerCase() + mn.substring(1);
         Map<String, Object> params = new HashMap<String, Object>();
         if (!"enterDate".equals(mn)) c.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式
         else c.setCellType(Cell.CELL_TYPE_NUMERIC);
         if (this.getCellValue(c).trim().equals("是")) {
           BeanUtils.copyProperty(obj, mn, 1);
         } else if (this.getCellValue(c).trim().equals("否")) {
           BeanUtils.copyProperty(obj, mn, 0);
         } else BeanUtils.copyProperty(obj, mn, this.getCellValue(c));
       }
       objs.add(obj);
     }
   } catch (InstantiationException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (NumberFormatException e) {
     e.printStackTrace();
     logger.error(e);
   }
   return objs;
 }
Exemplo n.º 17
0
  public String execute() {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (photo == null) return "setinfo";
    String uploadPath = "/var/www/uploadres";
    String photoName = session.getAttribute("username") + this.getPhotoFileName();
    File toPhotoFile = new File(new File(uploadPath), photoName);

    if (!toPhotoFile.getParentFile().exists()) toPhotoFile.getParentFile().mkdirs();
    try {
      FileUtils.copyFile(photo, toPhotoFile);
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        try {
          Connection conn = DriverManager.getConnection(url, user, pwd);
          Statement stmt = conn.createStatement();
          String sql =
              "UPDATE Users SET photo = '"
                  + photoName
                  + "' WHERE username='******'";
          stmt.execute(sql);
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return "setinfo";
  }
Exemplo n.º 18
0
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
Exemplo n.º 19
0
 public void buildClassifiers() {
   for (String tag : datasetsPerTag.keySet()) {
     // nl.openconvert.log.ConverterLog.defaultLog.println("Build classifier for " + tag);
     Dataset d = datasetsPerTag.get(tag);
     Classifier c = null;
     try {
       c = (Classifier) classifierClass.newInstance();
       c.setType(classifierType);
     } catch (InstantiationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     c.setType(classifierType);
     classifiersPerTag.put(tag, c);
     c.train(d, MAX_ITEMS_USED);
   }
   tagsSorted = new ArrayList<String>(datasetsPerTag.keySet());
   Collections.sort(tagsSorted);
 }
Exemplo n.º 20
0
  /**
   * The main method.
   *
   * @param args the arguments
   */
  public static void main(String[] args) {
    Questionnaire quiz = new Questionnaire();
    try {
      quiz.initQuestionnaire("question_tolkien.txt");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    new QuestionnaireUI(quiz);
  }
Exemplo n.º 21
0
  /**
   * Gets the current scoreboard and prints the users' names and scores in descending order.
   *
   * @return true if the scoreboard is printed successfully
   */
  private boolean getScoreboard() {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      conn =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/getoffthecouch", "XXXXXX", "XXXXXX");

      Statement getScoresStmt = conn.createStatement();
      String getScoresQuery =
          "SELECT user_id, user_name, total_score FROM user ORDER BY total_score DESC";
      ResultSet getScoresResult = getScoresStmt.executeQuery(getScoresQuery);
      String userId = "";
      String userName = "";
      int totalScore = -1;
      while (getScoresResult.next()) {
        userId = getScoresResult.getString("user_id");
        userName = getScoresResult.getString("user_name");
        totalScore = getScoresResult.getInt("total_score");
        out.println(userId + "|" + userName + "|" + totalScore);
      }
      getScoresStmt.close();
      return true;
    } catch (InstantiationException e) {
      e.printStackTrace(out);
      return false;
    } catch (IllegalAccessException e) {
      e.printStackTrace(out);
      return false;
    } catch (ClassNotFoundException e) {
      e.printStackTrace(out);
      return false;
    } catch (SQLException e) {
      e.printStackTrace(out);
      return false;
    }
  }
Exemplo n.º 22
0
 /** @param loader The SplitterLoader used to load the compiled source. Must not be null. */
 public void load(SplitterLoader loader) {
   Class tempClass = loader.load_Class(className, directory + className + ".class");
   if (tempClass != null) {
     try {
       splitter = (Splitter) tempClass.newInstance();
     } catch (ClassFormatError ce) {
       ce.printStackTrace(System.out);
     } catch (InstantiationException ie) {
       ie.printStackTrace(System.out);
     } catch (IllegalAccessException iae) {
       iae.printStackTrace(System.out);
     }
     DummyInvariant dummy = new DummyInvariant(null);
     dummy.setFormats(
         daikonFormat,
         javaFormat,
         escFormat,
         simplifyFormat,
         ioaFormat,
         jmlFormat,
         dbcFormat,
         dummyDesired);
     splitter.makeDummyInvariant(dummy);
     errorMessage = "Splitter exists " + this.toString();
     exists = true;
   } else {
     errorMessage =
         "No class data for "
             + this.toString()
             + ", to be loaded from "
             + directory
             + className
             + ".class";
     exists = false;
   }
 }
Exemplo n.º 23
0
  public boolean connect(Onion options, OobdBus receiveListener) {
    msgReceiver = receiveListener;
    System.out.println("Starting Bluetooth Detection and Device Pairing");
    if (mBluetoothAdapter == null) {
      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if (mBluetoothAdapter == null) {
        Log.w(this.getClass().getSimpleName(), "Bluetooth not supported.");
        return false;
      }
      if (!mBluetoothAdapter.isEnabled()) {
        Log.w(this.getClass().getSimpleName(), "Bluetooth switched off.");
        return false;
      }
    }

    obdDevice = mBluetoothAdapter.getRemoteDevice(BTAddress);

    if (obdDevice != null) { // Get a BluetoothSocket to connect
      // with the given BluetoothDevice
      try {
        Log.v(this.getClass().getSimpleName(), "Device " + obdDevice.getName());
        java.lang.reflect.Method m =
            obdDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        // "createInsecureRfcommSocket", new Class[] { int.class });
        serialPort = null;
        serialPort = (BluetoothSocket) m.invoke(obdDevice, 1);

        if (serialPort != null) {
          try {
            mBluetoothAdapter.cancelDiscovery();
            serialPort.connect();
            Log.d("OOBD:Bluetooth", "Bluetooth connected");
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();

            OOBDApp.getInstance().displayToast("Bluetooth connected");

            myThread =
                new Thread() {

                  @Override
                  public void run() {
                    byte[] buffer = new byte[1024]; // buffer store
                    // for the
                    // stream
                    int bytes; // bytes returned from read()

                    // Keep listening to the InputStream until an
                    // exception occurs
                    Log.d("OOBD:Bluetooth", "receiver task runs");
                    while (true) {
                      if (inputStream != null) {
                        try {
                          // Read from the InputStream
                          bytes = inputStream.read(buffer);
                          if (bytes > 0) {
                            Log.v(this.getClass().getSimpleName(), "Debug: received something");
                            String recString = new String(buffer);
                            recString = recString.substring(0, bytes);
                            msgReceiver.receiveString(recString);
                          }
                        } catch (IOException e) {
                          break;
                        }
                      } else {
                        try {
                          Thread.sleep(100);
                        } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                        }
                      }
                    }
                  }
                };
            myThread.start();
            return true;
          } catch (IOException ex) {
            Log.e(this.getClass().getSimpleName(), "Error: Could not connect to socket.", ex);
            OOBDApp.getInstance().displayToast("Bluetooth NOT connected!");
          }
        } else {
          Log.e("OOBD:Bluetooth", "Bluetooth NOT connected!");
          OOBDApp.getInstance().displayToast("Bluetooth NOT connected!");
          if (serialPort != null) {
            try {
              serialPort.close();
            } catch (IOException closeEx) {
            }
          }
          return false;
        }
        // do not yet connect. Connect before calling the
        // socket.
      } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return false;
  }
Exemplo n.º 24
0
 private void dump() throws IOException {
   lookupMethod = null;
   try {
     lookupMethod = catalog.getClass().getMethod("lookup", new Class[] {java.lang.String.class});
   } catch (NoSuchMethodException e) {
   } catch (SecurityException e) {
   }
   Method pluralMethod = null;
   try {
     pluralMethod = catalog.getClass().getMethod("get_msgid_plural_table", new Class[0]);
   } catch (NoSuchMethodException e) {
   } catch (SecurityException e) {
   }
   Field pluralField = null;
   try {
     pluralField = catalog.getClass().getField("plural");
   } catch (NoSuchFieldException e) {
   } catch (SecurityException e) {
   }
   // Search for the header entry.
   {
     Object header_entry = null;
     Enumeration keys = catalog.getKeys();
     while (keys.hasMoreElements())
       if ("".equals(keys.nextElement())) {
         header_entry = lookup("");
         break;
       }
     // If there is no header entry, fake one.
     // FIXME: This is not needed; right after po_lex_charset_init set
     // the PO charset to UTF-8.
     if (header_entry == null) header_entry = "Content-Type: text/plain; charset=UTF-8\n";
     dumpMessage("", null, header_entry);
   }
   // Now the other messages.
   {
     Enumeration keys = catalog.getKeys();
     Object plural = null;
     if (pluralMethod != null) {
       // msgfmt versions > 0.13.1 create a static get_msgid_plural_table()
       // method.
       try {
         plural = pluralMethod.invoke(catalog, new Object[0]);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       } catch (InvocationTargetException e) {
         e.getTargetException().printStackTrace();
       }
     } else if (pluralField != null) {
       // msgfmt versions <= 0.13.1 create a static plural field.
       try {
         plural = pluralField.get(catalog);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       }
     }
     if (plural instanceof String[]) {
       // A GNU gettext created class with plural handling, Java2 format.
       int i = 0;
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         Object value = lookup(key);
         String key_plural = (value instanceof String[] ? ((String[]) plural)[i++] : null);
         if (!"".equals(key)) dumpMessage(key, key_plural, value);
       }
       if (i != ((String[]) plural).length)
         throw new RuntimeException("wrong plural field length");
     } else if (plural instanceof Hashtable) {
       // A GNU gettext created class with plural handling, Java format.
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         if (!"".equals(key)) {
           Object value = lookup(key);
           String key_plural =
               (value instanceof String[] ? (String) ((Hashtable) plural).get(key) : null);
           dumpMessage(key, key_plural, value);
         }
       }
     } else if (plural == null) {
       // No plural handling.
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         if (!"".equals(key)) dumpMessage(key, null, lookup(key));
       }
     } else throw new RuntimeException("wrong plural field value");
   }
 }
Exemplo n.º 25
0
  public static void setEntity(Plan ent, Map attributes) {
    Map currentMap =
        (Map) RenderComponentManager.retrieveIDs("Plan", ent.getPrefs(attributes).getView());
    current = ent.getPrefs(attributes).getView();
    if (ent != null
        && currentMap.get("_attributes_") != null
        && currentMap.get("_attributes_") instanceof ingenias.editor.rendererxml.AttributesPanel) {

      ((ingenias.editor.rendererxml.AttributesPanel) currentMap.get("_attributes_")).setEntity(ent);
    }

    if (currentMap.get("Tasks") != null
        && currentMap.get("Tasks") instanceof ingenias.editor.rendererxml.CollectionPanel) {
      try {
        ((ingenias.editor.rendererxml.CollectionPanel) currentMap.get("Tasks"))
            .setCollection("Tasks", ent.Tasks, ent.Tasks.getType());
      } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
      } catch (IllegalAccessException ex) {
        ex.printStackTrace();
      }
    }

    if (currentMap.get("Tasks") != null
        && currentMap.get("Tasks") instanceof ingenias.editor.rendererxml.CollectionPanel) {
      try {
        ((ingenias.editor.rendererxml.CollectionPanel) currentMap.get("Tasks"))
            .setCollection("Tasks", ent.Tasks, ent.Tasks.getType());
      } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
      } catch (IllegalAccessException ex) {
        ex.printStackTrace();
      }
    }

    if (currentMap.get("Tasks") != null) {
      if (ent != null && ent.getTasks() != null) {
        if (currentMap.get("Tasks") instanceof javax.swing.JLabel) {
          ((javax.swing.JLabel) (currentMap).get("Tasks")).setText(ent.getTasks().toString());
        } else {
          if (currentMap.get("Tasks") instanceof javax.swing.text.JTextComponent)
            ((javax.swing.text.JTextComponent) (currentMap).get("Tasks"))
                .setText(ent.getTasks().toString());
        }
      } else {
        if (currentMap.get("Tasks") instanceof javax.swing.JLabel)
          ((javax.swing.JLabel) (currentMap).get("Tasks")).setText("");
        else {
          if (!(currentMap.get("Tasks") instanceof ingenias.editor.rendererxml.CollectionPanel))
            ((javax.swing.text.JTextComponent) (currentMap).get("Tasks")).setText("");
        }
      }
    }

    if (currentMap.get("Id") != null) {
      if (ent != null && ent.getId() != null) {
        if (currentMap.get("Id") instanceof javax.swing.JLabel) {
          ((javax.swing.JLabel) (currentMap).get("Id")).setText(ent.getId().toString());
        } else {
          if (currentMap.get("Id") instanceof javax.swing.text.JTextComponent)
            ((javax.swing.text.JTextComponent) (currentMap).get("Id"))
                .setText(ent.getId().toString());
        }
      } else {
        if (currentMap.get("Id") instanceof javax.swing.JLabel)
          ((javax.swing.JLabel) (currentMap).get("Id")).setText("");
        else {
          if (!(currentMap.get("Id") instanceof ingenias.editor.rendererxml.CollectionPanel))
            ((javax.swing.text.JTextComponent) (currentMap).get("Id")).setText("");
        }
      }
    }
  }
Exemplo n.º 26
0
 public Object __parse_response__(String resp) throws RemoteException {
   JsonParser parser = new JsonParser();
   JsonElement main_response = (JsonElement) parser.parse(resp);
   if (main_response.isJsonArray()) {
     List<Object> res = new Vector<Object>();
     for (Object o : main_response.getAsJsonArray()) {
       res.add(__parse_response__(gson.toJson(o)));
     }
     return res;
   }
   JsonObject response = main_response.getAsJsonObject();
   if (response.has("error")) {
     JsonObject e = response.get("error").getAsJsonObject().get("data").getAsJsonObject();
     throw new RemoteException(e.get("exception").getAsString(), e.get("message").getAsString());
   }
   JsonElement value = response.get("result");
   String valuestr = gson.toJson(response.get("result"));
   if (valuestr.contains("hash:")) {
     Class<? extends RpcClient> klass = this.getClass();
     try {
       Constructor<? extends RpcClient> m =
           klass.getDeclaredConstructor(String.class, String.class);
       String new_endpoint = gson.fromJson(value, String.class);
       return m.newInstance(this.base_endpoint, new_endpoint.replace("hash:", ""));
     } catch (NoSuchMethodException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (IllegalArgumentException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (InstantiationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (InvocationTargetException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     }
   } else if (valuestr.contains("funcs")) {
     return gson.fromJson(valuestr, Interface.class);
   }
   if (value.isJsonPrimitive()) {
     JsonPrimitive val = value.getAsJsonPrimitive();
     if (val.isBoolean()) {
       return val.getAsBoolean();
     } else if (val.isNumber()) {
       return val.getAsNumber();
     } else if (val.isString()) {
       DateTimeFormatter dtparser = ISODateTimeFormat.dateHourMinuteSecond();
       try {
         return dtparser.parseDateTime(val.getAsString());
       } catch (Exception ex) {
       }
       return val.getAsString();
     } else {
       return null;
     }
   } else if (value.isJsonNull()) {
     return null;
   } else if (value.isJsonObject() && !value.getAsJsonObject().has("__meta__")) {
     return gson.fromJson(value, HashMap.class);
   } else if (value.isJsonArray()) {
     if (value.getAsJsonArray().size() == 0) return new LinkedList();
     JsonElement obj = value.getAsJsonArray().get(0);
     if (obj.isJsonObject()) {
       if (!obj.getAsJsonObject().has("__meta__")) {
         return gson.fromJson(value, LinkedList.class);
       }
     }
   }
   return __resolve_references__(valuestr);
 }
Exemplo n.º 27
0
  public ReverseFlashCard() {
    // basic init
    setTitle("WayMemo -Reverse Flash Card Mode");
    this.setSize(800, 600);
    paneCenter = new JPanel(new GridLayout(7, 1));

    add(ln, "North");
    add(paneCenter, "Center");
    add(b2, "West");
    add(bReset, "South");
    add(b1, "East");
    paneCenter.add(l1);
    paneCenter.add(l2);
    paneCenter.add(l3);
    paneCenter.add(l4);
    paneCenter.add(l5);
    paneCenter.add(b3);
    paneCenter.add(pMark);
    pMark.add(bMark);
    pMark.add(bUnMark);
    pMark.add(lt);

    // text area init

    Utility.initTextAreaView(l1);
    Utility.initTextAreaView(l2);
    Utility.initTextAreaView(l3);
    Utility.initTextAreaView(l4);
    Utility.initTextAreaView(l5);

    // action

    //
    Action actionNext =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            num++;
            wordDisplay();
          }
        };
    b1.getInputMap().put(KeyStroke.getKeyStroke("C"), "pressed");
    b1.getActionMap().put("released", actionNext);
    //
    Action actionBack =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            num--;
            wordDisplay();
          }
        };
    b2.getInputMap().put(KeyStroke.getKeyStroke("Z"), "pressed");
    b2.getActionMap().put("released", actionBack);
    //
    Action actionShow =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            l1.setText(dtr[num]);
            l3.setText(d2[num]);
            l4.setText(d3[num]);
            l5.setText(d4[num]);
          }
        };
    b3.getInputMap().put(KeyStroke.getKeyStroke("X"), "pressed");
    b3.getActionMap().put("released", actionShow);
    //
    //
    Action actionMark =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            d1[num] = "[MARKED*]" + d1[num];
            l2.setText(d1[num]);
          }
        };
    bMark.getInputMap().put(KeyStroke.getKeyStroke("S"), "pressed");
    bMark.getActionMap().put("released", actionMark);
    //
    //
    //
    Action actionUnmark =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            d1[num] = od1[num];
            l2.setText(d1[num]);
          }
        };
    bUnMark.getInputMap().put(KeyStroke.getKeyStroke("F2"), "pressed");
    bUnMark.getActionMap().put("released", actionUnmark);
    //
    //
    Action actionReset =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            num = 0;
            wordDisplay();
          }
        };
    bReset.getInputMap().put(KeyStroke.getKeyStroke("r"), "pressed");
    bReset.getActionMap().put("released", actionReset);
    //
    //
    b1.setMnemonic(KeyEvent.VK_C);
    b2.setMnemonic(KeyEvent.VK_Z);
    b3.setMnemonic(KeyEvent.VK_X);
    bMark.setMnemonic(KeyEvent.VK_S);
    bUnMark.setMnemonic(KeyEvent.VK_D);
    bReset.setMnemonic(KeyEvent.VK_R);

    b1.addActionListener(actionNext);
    b2.addActionListener(actionBack);
    b3.addActionListener(actionShow);
    bReset.addActionListener(actionReset);
    bMark.addActionListener(actionMark);
    bUnMark.addActionListener(actionUnmark);
    //
    //
    try {
      this.fileScan(new OpenFileDTR().getPathDTR());
    } catch (IOException e) {
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 28
0
  /**
   * Gets the invitations from the database and prints their details.
   *
   * @param facebookId - Facebook id of the user
   * @return true if the list of invitation details are printed successfully
   */
  private boolean getInvitations(String facebookId) {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      conn =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/getoffthecouch", "XXXXXX", "XXXXXX");

      Statement checkStmt = conn.createStatement();
      String checkQuery =
          "SELECT COUNT(*) FROM invitation WHERE invitee='" + facebookId + "' AND confirmed=0";
      ResultSet checkQueryResult = checkStmt.executeQuery(checkQuery);
      checkQueryResult.next();
      int count = checkQueryResult.getInt(1);

      if (count == 0) {
        return false;
      }

      Statement getInvitationsStmt = conn.createStatement();
      String getInvitationsQuery =
          "SELECT i.inv_id, l.loc_name, e.date, e.time, u.user_name, e.total_score, l.cat_id, i.event_id, l.photo_thumb "
              + "FROM invitation i, location l, event e, user u WHERE i.event_id=e.event_id AND e.loc_id = l.loc_id "
              + "AND i.invitee='"
              + facebookId
              + "' AND u.user_id=i.inviter AND i.confirmed=0";
      ResultSet getInvitationsResult = getInvitationsStmt.executeQuery(getInvitationsQuery);
      int invitationId = -1;
      String locationName = "";
      String dateAndTime = "";
      String userName = "";
      int totalScore = -1;
      int categoryId = -1;
      int eventId = -1;
      String photoThumb = "";

      while (getInvitationsResult.next()) {
        invitationId = getInvitationsResult.getInt("inv_id");
        locationName = getInvitationsResult.getString("loc_name");
        String date = getInvitationsResult.getString("date");
        String time = getInvitationsResult.getString("time");
        SimpleDateFormat sqlFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
          Date dateObject = sqlFormatter.parse(date + " " + time);
          SimpleDateFormat outputFormatter = new SimpleDateFormat("d MMM yyyy, HH:mm");
          dateAndTime = outputFormatter.format(dateObject);
        } catch (ParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        userName = getInvitationsResult.getString("user_name");
        totalScore = getInvitationsResult.getInt("total_score");
        categoryId = getInvitationsResult.getInt("cat_id");
        eventId = getInvitationsResult.getInt("event_id");
        photoThumb = getInvitationsResult.getString("photo_thumb");
        String output =
            invitationId
                + "|"
                + locationName
                + "|"
                + dateAndTime
                + "|"
                + userName
                + "|"
                + totalScore
                + "|"
                + categoryId
                + "|"
                + eventId
                + "|"
                + photoThumb;
        out.println(output);
      }
      getInvitationsStmt.close();
      return true;
    } catch (InstantiationException e) {
      e.printStackTrace(out);
      return false;
    } catch (IllegalAccessException e) {
      e.printStackTrace(out);
      return false;
    } catch (ClassNotFoundException e) {
      e.printStackTrace(out);
      return false;
    } catch (SQLException e) {
      e.printStackTrace(out);
      return false;
    }
  }
Exemplo n.º 29
0
 private Workbook handleExcel(List objs, Class clz, boolean isXssf, String message) {
   XSSFWorkbook wb = null;
   try {
     if (isXssf) {
       XSSFWorkbook w = new XSSFWorkbook();
     } else {
       HSSFWorkbook w = new HSSFWorkbook();
     }
     wb = new XSSFWorkbook();
     XSSFDataFormat format = wb.createDataFormat();
     XSSFSheet sheet = wb.createSheet(message + "备份记录"); // 取excel工作表对象
     XSSFCellStyle cellStyle = wb.createCellStyle(); // 设置excel单元格样式
     XSSFCellStyle passwordCellStyle = wb.createCellStyle(); // 设置密码单元格样式
     XSSFDataFormat passwordFormat = wb.createDataFormat();
     passwordCellStyle.setDataFormat(passwordFormat.getFormat(";;;"));
     List<ExcelHeader> headers = getHeaderList(clz);
     Collections.sort(headers);
     sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) (headers.size() - 1)));
     Row r0 = sheet.createRow(0);
     Cell cell = r0.createCell(0);
     r0.setHeightInPoints(28);
     cell.setCellValue(message + "备份记录");
     Row r = sheet.createRow(1);
     r.setHeightInPoints(25);
     cell.setCellStyle(cellStyle);
     // 输出标题
     for (int i = 0; i < headers.size(); i++) {
       Cell cell1 = r.createCell(i);
       if (headers.get(i).getTitle().equals("密码")) cell1.setCellStyle(passwordCellStyle);
       else cell1.setCellStyle(cellStyle);
       cell1.setCellValue(headers.get(i).getTitle());
     }
     Object obj = null;
     // 输出用户资料信息
     if (message.indexOf("用户资料 ") > 0) {
       sheet.setColumnWidth(3, 32 * 150);
       sheet.setColumnWidth(4, 32 * 110);
       sheet.setColumnWidth(7, 32 * 120);
       for (int i = 0; i < objs.size(); i++) {
         r = sheet.createRow(i + 2);
         obj = objs.get(i);
         for (int j = 0; j < headers.size(); j++) {
           Cell cell2 = r.createCell(j);
           copyDefaultCellStyle(null, cell2, cellStyle, 0);
           if (getMethodName(headers.get(j)).equals("nabled"))
             cell2.setCellValue(BeanUtils.getProperty(obj, "enabled"));
           else if (getMethodName(headers.get(j)).equals("password")) {
             cell2.setCellStyle(passwordCellStyle);
             cell2.setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
           } else cell2.setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
         }
       }
     }
     // 输出房间使用信息数据
     else {
       sheet.setColumnWidth(0, 32 * 80);
       sheet.setColumnWidth(2, 32 * 100);
       sheet.setColumnWidth(3, 32 * 190);
       sheet.setColumnWidth(4, 32 * 190);
       sheet.setColumnWidth(5, 32 * 190);
       sheet.setColumnWidth(10, 32 * 130);
       for (int i = 0; i < objs.size(); i++) {
         r = sheet.createRow(i + 2);
         obj = objs.get(i);
         for (int j = 0; j < headers.size(); j++) {
           Cell cell2 = r.createCell(j);
           if (j == 3 || j == 4 || j == 5) {
             XSSFCellStyle cs3 = wb.createCellStyle();
             cell2.setCellValue(new Date());
             copyDefaultCellStyle(format, cell2, cs3, 1);
           }
           if (j == 10) {
             XSSFCellStyle cs2 = wb.createCellStyle();
             copyDefaultCellStyle(format, cell2, cs2, 2);
           }
           copyDefaultCellStyle(null, cell2, cellStyle, 0);
           cell2.setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
         }
       }
     }
     // 设置行列的默认宽度和高度
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
     logger.error(e);
   }
   return wb;
 }
Exemplo n.º 30
0
  @Override
  public void addJob(
      String jobName,
      byte type,
      String pathToJar,
      String className,
      String pathToData,
      String[] peers,
      int parNumber,
      int numberOfReducers,
      HashMap<String, Integer> finishedMappers)
      throws RemoteException {
    SysLogger.getInstance().info("Job " + jobName + " started");

    Logger logger = null;
    try {
      logger = new Logger(0, "..\\log\\WorkerNode.log");
    } catch (IncorrectLogFileException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    DFSClient dfs = DFSClient.getInstance();
    try {
      dfs.init("localhost", 20000, logger);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    String localPathToJar = "..\\tasks\\" + jobName + ".jar";
    File jarFile = new File(localPathToJar);
    if (jarFile.exists()) {
      jarFile.delete();
    }
    String localPathToData = "..\\tasks\\" + jobName + ".dat";
    File dataFile = new File(localPathToData);
    if (dataFile.exists()) {
      dataFile.delete();
    }
    try {
      dfs.downloadFile(pathToJar, localPathToJar);
      if (type == MapReduce.TYPE_MAPPER) {
        dfs.downloadFile(pathToData, localPathToData);
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    try {
      URL url = new URL("file:///" + jarFile.getAbsolutePath());
      URLClassLoader classLoader = new URLClassLoader(new URL[] {url});
      // todo make this
      Class c = classLoader.loadClass(className);

      MapReduce jobObject = (MapReduce) c.newInstance();
      Job job = null;
      if (type == MapReduce.TYPE_MAPPER) {
        job =
            new Job(
                jobName,
                type,
                jobObject,
                dataFile.getAbsolutePath(),
                peers,
                parNumber,
                numberOfReducers,
                finishedMappers);
      } else if (type == MapReduce.TYPE_REDUCER) {
        job =
            new Job(
                jobName,
                type,
                jobObject,
                pathToData,
                peers,
                parNumber,
                numberOfReducers,
                finishedMappers);
      }
      jobList.put(jobName, job);

      job.start(); // start new thread
      // return control
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }