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();
    }
  }
  /*
   * 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();
    }
  }
  /**
   * 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();
    }
  }
Beispiel #4
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;
    }
  }
Beispiel #5
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);
      }
    }
  }
Beispiel #6
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();
    }
  }
Beispiel #7
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;
 }
Beispiel #8
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";
  }
 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;
 }
Beispiel #10
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);
 }
 /** @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;
   }
 }
Beispiel #12
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;
    }
  }
Beispiel #13
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();
    }
  }
  /**
   * 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;
    }
  }
Beispiel #15
0
  public static void main(String[] args) throws ClassNotFoundException, IOException {

    /*
     * process command line arguments
     */

    if (args.length < 1) {
      usage();
      return;
    }

    boolean verbose = false;

    for (int i = 0; i < args.length; ++i) {
      String arg = args[i];
      if (arg.startsWith("-")) {
        switch (arg.charAt(1)) {
          case 'p':
            protocolVersion = Integer.decode(arg.substring(2)).intValue();
            break;

          case 's':
            serialize = true;
            serialStreamFileName = arg.substring(2);
            break;

          case 'd':
            deserialize = true;
            serialStreamFileName = arg.substring(2);
            break;

          case 'n':
            instances = Integer.decode(arg.substring(2)).intValue();
            instances = Math.min(instances, 1);
            break;

          case 'v':
            verbose = true;
            break;

          default:
            System.err.println("unknown option \"" + arg + "\"");
            usage();
            return;
        }
      } else {
        if (testClassName == null) testClassName = arg;
        else {
          System.err.println("invalid argument \"" + arg + "\"");
          return;
        }
      }
    }

    Class testClass = null;
    if (testClassName != null)
      try {
        testClass = Class.forName(testClassName);
      } catch (ClassNotFoundException e) {
      }

    if (serialStreamFileName == null) {
      // If no filename specified only makes sense to perform
      // both serialization and deserialization.
      serialize = deserialize = true;
    }

    /*
     * create object to be serialized
     */

    ByteArrayOutputStream baos = null;
    if (serialize) {
      OutputStream os = null;
      if (serialStreamFileName == null) {
        os = baos = new ByteArrayOutputStream(1024);
      } else os = new FileOutputStream(serialStreamFileName);

      try {
        Object obj;
        ObjectOutputStream out = new VerboseObjectOutputStream(os, verbose);
        try {
          out.useProtocolVersion(protocolVersion);
        } catch (NoSuchMethodError e) {
          // JVM 1.1 does not have this method.
        }
        if (testClass == null) {
          if (testClassName != null) throw new ClassNotFoundException(testClassName);
          else throw new Error("No classname provided to serialize");
        }
        for (int i = 0; i < instances; i++) {
          try {
            obj = testClass.newInstance();
            long start = System.currentTimeMillis();
            out.writeObject(obj);
            long duration = System.currentTimeMillis() - start;
            System.out.println(
                "Time " + duration + " millisecs " + "(" + (duration / 1000.0) + " secs)");
            System.out.println("Serialize " + obj.toString());
          } catch (IllegalAccessException e) {
            System.err.println("Class " + testClassName + " does not have a public constructor.");
            return;
          } catch (InstantiationException e) {
            System.err.println("Exception creating instance of " + testClassName + ":");
            e.printStackTrace();
            return;
          }
        }

        out.close();
      } catch (IOException e) {
        System.err.println("Exception occurred during serialization: ");
        e.printStackTrace();
        return;
      }
    }

    if (deserialize) {
      InputStream is = null;
      if (baos != null) {
        is = new ByteArrayInputStream(baos.toByteArray());
      } else if (serialStreamFileName != null) {
        is = new FileInputStream(serialStreamFileName);
      } else {
        System.err.println("No input stream specified on commandline.");
        return;
      }

      ObjectInputStream in = null;
      try {
        in = new VerboseObjectInputStream(is, verbose);
        long start = System.currentTimeMillis();
        for (int i = 0; i < instances; i++) {
          try {
            Object obj = in.readObject();
            System.out.println("DeSerialize " + obj.toString());
          } catch (OptionalDataException e) {
            if (!e.eof) System.out.println("Skipping " + e.length + " bytes");
            in.skip(e.length);
          }
        }
        long duration = System.currentTimeMillis() - start;
        System.out.println(
            "Time " + duration + " millisecs " + "(" + (duration / 1000.0) + " secs)");
      } catch (EOFException e) {
      } catch (IOException e) {
        System.err.println("Exception occurred reading object. ");
        e.printStackTrace();
      } finally {
        if (in != null) {
          in.close();
        }
      }
    }
    System.exit(0);
  }
Beispiel #16
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);
 }
Beispiel #17
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();
    }
  }