Example #1
0
  private ArrayList GetFolderTree(String s_Dir, String s_Flag, int n_Indent, int n_TreeIndex) {
    String s_List = "";
    ArrayList aSubFolders = new ArrayList();

    File file = new File(s_Dir);
    File[] filelist = file.listFiles();

    if (filelist != null && filelist.length > 0) {
      for (int i = 0; i < filelist.length; i++) {
        if (filelist[i].isDirectory()) {
          aSubFolders.add(filelist[i].getName());
        }
      }

      int n_Count = aSubFolders.size();
      String s_LastFlag = "";
      String s_Folder = "";
      for (int i = 1; i <= n_Count; i++) {
        if (i < n_Count) {
          s_LastFlag = "0";
        } else {
          s_LastFlag = "1";
        }

        s_Folder = aSubFolders.get(i - 1).toString();
        s_List =
            s_List
                + "arr"
                + s_Flag
                + "["
                + String.valueOf(n_TreeIndex)
                + "]=new Array(\""
                + s_Folder
                + "\","
                + String.valueOf(n_Indent)
                + ", "
                + s_LastFlag
                + ");\n";
        n_TreeIndex = n_TreeIndex + 1;
        ArrayList a_Temp =
            GetFolderTree(s_Dir + s_Folder + sFileSeparator, s_Flag, n_Indent + 1, n_TreeIndex);
        s_List = s_List + a_Temp.get(0).toString();
        n_TreeIndex = Integer.valueOf(a_Temp.get(1).toString()).intValue();
      }
    }

    ArrayList a_Return = new ArrayList();
    a_Return.add(s_List);
    a_Return.add(String.valueOf(n_TreeIndex));
    return a_Return;
  }
 /** Creates a new bee widget. */
 public HappyMagicalRainbowBee() {
   shape = new Box(WIDTH, HEIGHT);
   body = new Body(shape, MASS);
   loadImages();
   icon = new ImageIcon();
   icon.setImage(frames.get(0));
   setPosition(new Vector2f(0, 0));
 }
 public void trav(ArrayList nodes, node cur) {
   node temp;
   while (!nodes.isEmpty()) {
     temp = (node) nodes.get(0);
     if (temp.getLevel() - 1 == cur.getLevel()) {
       nodes.remove(0);
       cur.addChild(temp);
       trav(nodes, temp);
     } else {
       return;
     }
   }
 }
 /**
  * Draws the widget.
  *
  * @param g The object that draws things.
  */
 public void draw(Graphics2D screen) {
   // Animate!
   if (System.nanoTime() - timestamp >= CENTISECOND * 50) {
     timestamp = System.nanoTime();
     if (image == frames.get(0)) {
       image = frames.get(1);
     } else {
       image = frames.get(0);
     }
   }
   ROVector2f position = body.getPosition();
   float angle = body.getRotation();
   boolean hflip = false;
   boolean vflip = false;
   if (currentDirection == Direction.WEST) {
     hflip = false;
   } else if (currentDirection == Direction.EAST) {
     hflip = true;
   } else if (currentDirection == Direction.NORTH) {
     angle += Math.PI / 2;
     vflip = false;
   } else if (currentDirection == Direction.SOUTH) {
     angle += Math.PI / 2;
     vflip = true;
   }
   drawImage(
       position.getX(),
       position.getY(),
       getWidth(),
       getHeight(),
       angle,
       hflip,
       vflip,
       image,
       screen);
 }
  public void recreateTree() {
    System.out.println("Recreating tree");
    ArrayList nodes = new ArrayList();
    String attr, crit, result;
    int level;
    node leaf;
    while (!list.isEmpty()) {
      if (((String) list.remove(0)).compareTo("Node") == 0) {
        leaf = new node();
        attr = (String) list.remove(0);
        // System.out.println("ATTR:"+attr);
        crit = (String) list.remove(0);
        try {
          level = (new Double(crit)).intValue();
          crit = null;
        } catch (Exception e) {
          // System.out.println("crit:"+crit);
          level = (new Double((String) list.remove(0))).intValue();
        }
        // System.out.println("lvl:"+level);
        if (level > depth) {
          depth = level;
        }
        if (((String) list.get(0)).compareTo("Node") != 0) {
          result = (String) list.remove(0);
          leaf.setResult(result);
        }
        leaf.setSplitCriteria(crit, 0);
        leaf.setLevel(level);
        leaf.setAttr(attr);

        if (attr.compareTo("_root") == 0) {
          root = leaf;
        } else {

          nodes.add(leaf);
        }
      }
    }
    depth++;
    levelCount(nodes);

    System.out.println("Linking " + nodes.size() + " tree nodes");
    trav(nodes, root);
  }
  /** Resets the widget to start state. */
  public void resetWidget() {
    // Reset has been made, so we CAN activate this later.
    reset = true;
    // Make inactive
    active = false;
    // Not collided.
    collided = false;

    bounces = 0;
    currentDirection = direction;
    image = frames.get(0);
    body.setEnabled(false);
    // Move to initial position.
    body.set(shape, MASS);
    body.setPosition(position.x + WIDTH / 2, position.y + HEIGHT / 2);

    // Make sure the gameplay didn't mess with any initial properties.
    body.setCanRest(true);
    body.setDamping(0.0f);
    body.setFriction(0.01f);
    body.setGravityEffected(false);
    body.setIsResting(true);
    body.setMoveable(true);
    body.setRestitution(1.5f);
    body.setRotatable(true);
    body.setRotation(0.0f);
    body.setRotDamping(0.0f);
    body.setMaxVelocity(50f, 50f);
    body.setForce(-body.getForce().getX(), -body.getForce().getY());
    if (currentDirection == Direction.WEST) {
      body.setForce(-MOVEMENT_SPEED, 0);
    } else if (currentDirection == Direction.EAST) {
      body.setForce(MOVEMENT_SPEED, 0);
    }
    if (currentDirection == Direction.NORTH) {
      body.setForce(0, -MOVEMENT_SPEED);
    } else if (currentDirection == Direction.SOUTH) {
      body.setForce(0, MOVEMENT_SPEED);
    }
    body.adjustVelocity(new Vector2f(-body.getVelocity().getX(), -body.getVelocity().getY()));
    body.adjustAngularVelocity(-body.getAngularVelocity());
  }
 public void levelCount(ArrayList nodes) {
   System.out.println("Doing level counts");
   spacing = new double[depth];
   for (int i = 0; i < depth; i++) {
     spacing[i] = 0;
   }
   spacing[0]++;
   node leaf;
   for (int i = 0; i < nodes.size(); i++) {
     leaf = (node) nodes.get(i);
     spacing[leaf.getLevel()]++;
   }
   max = 0;
   for (int i = 0; i < depth; i++) {
     if (spacing[i] > max) {
       max = spacing[i];
     }
     // System.out.println("Level "+i+" has "+spacing[i]+" nodes");
   }
 }
  public void removeBuilding(int i, int j) {

    if (tiles[i][j].getValue().equals("")) {
      JOptionPane.showMessageDialog(null, "There is no building here");
      return;
    }

    if (tiles[i][j].value.contains("-")) {
      String tText = tiles[i][j].value;
      i = Integer.parseInt(tText.split("-")[0]);
      j = Integer.parseInt(tText.split("-")[1]);
    }

    int index;
    for (index = 0; index < bb.size(); index++) {
      if (bb.get(index).getText().split("-")[0].equals(tiles[i][j].value)) {
        break;
      }
    }

    String temp = bb.get(index).getText();
    String[] parts = temp.split("-");
    int newQ = Integer.parseInt(parts[1]) + 1;

    Building tB = bList.get(0);
    for (int b = 0; b < bList.size(); b++) {
      if (bList.get(b).getName().equals(tiles[i][j].value)) {
        tB = bList.get(b);
        break;
      }
    }

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {

        if ((i + c + j + r) % 2 == 0) tiles[i + c][j + r].setBackground(new Color(102, 255, 51));
        else tiles[i + c][j + r].setBackground(new Color(51, 204, 51));

        tiles[i + c][j + r].setIcon(null);

        tiles[i + c][j + r].value = "";
        bb.get(index).setText(parts[0] + "-" + newQ);
      }
    }
  }
  public void insertBuilding(int i, int j, int index) {

    if (!tiles[i][j].getValue().equals("")) {
      JOptionPane.showMessageDialog(null, "There is already a building here");
      return;
    }

    String temp = bb.get(index).getText();
    String[] parts = temp.split("-");

    int newQ = Integer.parseInt(parts[1]) - 1;
    if (newQ < 0) return;

    Building tB = bList.get(0);
    for (int b = 0; b < bList.size(); b++) {
      if (bList.get(b).getName().equals(parts[0])) {
        tB = bList.get(b);
        // System.out.println("here");
        break;
      }
    }

    Image image = null;
    BufferedImage buffered;
    try {
      image = ImageIO.read(new File("images/" + tB.getName().replace(" ", "_") + ".png"));
      System.out.println("Loaded image");
    } catch (IOException e) {
      System.out.println("Failed to load image");
    }
    buffered = (BufferedImage) image;

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        if (i + c == 40 || j + r == 40) {
          JOptionPane.showMessageDialog(null, "Placing a building here would be out of bounds");
          return;
        }

        if (!tiles[i + c][j + r].getValue().equals("")) {
          JOptionPane.showMessageDialog(null, "Placing a building here will result to a overlap");
          return;
        }
      }
    }

    double w = buffered.getWidth() / tB.getQWidth();
    double h = buffered.getHeight() / tB.getQHeight();

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        tiles[i + c][j + r].setBackground(new Color(51, 204, 51));
        tiles[i + c][j + r].setIcon(
            new ImageIcon(
                resize(
                    buffered.getSubimage((int) w * r, (int) h * c, (int) w, (int) h),
                    tiles[i + c][j + r].getWidth(),
                    tiles[i + c][j + r].getHeight())));

        String tValue = (c == 0 && r == 0) ? tB.getName() : i + "-" + j;
        // System.out.println(tValue);
        tiles[i + c][j + r].setValue(tValue);
      }
    }

    // tiles[i][j].setBackground(Color.BLUE);
    bb.get(index).setText(parts[0] + "-" + newQ);
  }
  // Constructor connection receiving a socket number
  public ClientGUI(String host, int port, int udpPort) {

    super("Clash of Clans");
    defaultPort = port;
    defaultUDPPort = udpPort;
    defaultHost = host;

    // the server name and the port number
    JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3));
    tfServer = new JTextField(host);
    tfPort = new JTextField("" + port);
    tfPort.setHorizontalAlignment(SwingConstants.RIGHT);

    // CHAT COMPONENTS
    chatStatus = new JLabel("Please login first", SwingConstants.LEFT);
    chatField = new JTextField(18);
    chatField.setBackground(Color.WHITE);

    JPanel chatControls = new JPanel();
    chatControls.add(chatStatus);
    chatControls.add(chatField);
    chatControls.setBounds(0, 0, 200, 50);

    chatArea = new JTextArea("Welcome to the Chat room\n", 80, 80);
    chatArea.setEditable(false);
    JScrollPane jsp = new JScrollPane(chatArea);
    jsp.setBounds(0, 50, 200, 550);

    JPanel chatPanel = new JPanel(null);
    chatPanel.setSize(1000, 600);
    chatPanel.add(chatControls);
    chatPanel.add(jsp);

    // LOGIN COMPONENTS
    mainLogin = new MainPanel();
    mainLogin.add(new JLabel("Main Login"));

    usernameField = new JTextField("user", 15);
    passwordField = new JTextField("password", 15);
    login = new CButton("Login");
    login.addActionListener(this);

    sideLogin = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    sideLogin.add(usernameField);
    sideLogin.add(passwordField);
    sideLogin.add(login);

    // MAIN MENU COMPONENTS
    mainMenu = new MainPanel();
    mmLabel = new JLabel("Main Menu");
    timer = new javax.swing.Timer(1000, this);
    mainMenu.add(mmLabel);

    sideMenu = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmButton = new CButton("Customize Map");
    tmButton = new CButton("Troop Movement");
    gsButton = new CButton("Game Start");
    logout = new CButton("Logout");
    cmButton.addActionListener(this);
    tmButton.addActionListener(this);
    gsButton.addActionListener(this);
    logout.addActionListener(this);
    sideMenu.add(cmButton);
    // sideMenu.add(tmButton);
    sideMenu.add(gsButton);
    sideMenu.add(logout);

    // CM COMPONENTS
    mainCM = new MainPanel(new GridLayout(mapSize, mapSize));
    tiles = new Tile[mapSize][mapSize];
    int tileSize = mainCM.getWidth() / mapSize;
    for (int i = 0; i < mapSize; i++) {
      tiles[i] = new Tile[mapSize];
      for (int j = 0; j < mapSize; j++) {
        tiles[i][j] = new Tile(i, j);
        tiles[i][j].setPreferredSize(new Dimension(tileSize, tileSize));
        tiles[i][j].setSize(tileSize, tileSize);
        tiles[i][j].addActionListener(this);

        if ((i + j) % 2 == 0) tiles[i][j].setBackground(new Color(102, 255, 51));
        else tiles[i][j].setBackground(new Color(51, 204, 51));

        mainCM.add(tiles[i][j]);
      }
    }

    sideCM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmBack = new CButton("Main Menu");
    cmBack.setSize(150, 30);
    cmBack.setPreferredSize(new Dimension(150, 30));
    cmBack.addActionListener(this);
    sideCM.add(cmBack);

    // TM COMPONENTS
    mainTM = new MainPanel(null);
    mapTM = new Map(600);
    mapTM.setPreferredSize(new Dimension(600, 600));
    mapTM.setSize(600, 600);
    mapTM.setBounds(0, 0, 600, 600);
    mainTM.add(mapTM);

    sideTM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    tmBack = new CButton("Main Menu");
    tmBack.setSize(150, 30);
    tmBack.setPreferredSize(new Dimension(150, 30));
    tmBack.addActionListener(this);
    sideTM.add(tmBack);

    JRadioButton button;
    ButtonGroup group;

    ub = new ArrayList<JRadioButton>();
    group = new ButtonGroup();

    button = new JRadioButton("Barbarian");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    button = new JRadioButton("Archer");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    createBuildings();
    bb = new ArrayList<JRadioButton>();

    group = new ButtonGroup();

    JRadioButton removeButton = new JRadioButton("Remove Building");
    bb.add(removeButton);
    sideCM.add(removeButton);
    group.add(removeButton);

    for (int i = 0; i < bList.size(); i++) {
      button = new JRadioButton(bList.get(i).getName() + '-' + bList.get(i).getQuantity());
      bb.add(button);
      sideCM.add(button);
      group.add(button);
    }

    mainPanels = new MainPanel(new CardLayout());
    mainPanels.add(mainLogin, "Login");
    mainPanels.add(mainMenu, "Menu");
    mainPanels.add(mainCM, "CM");
    mainPanels.add(mainTM, "TM");

    sidePanels = new SidePanel(new CardLayout());
    sidePanels.add(sideLogin, "Login");
    sidePanels.add(sideMenu, "Menu");
    sidePanels.add(sideCM, "CM");
    sidePanels.add(sideTM, "TM");

    JPanel mainPanel = new JPanel(null);
    mainPanel.setSize(1000, 600);
    mainPanel.add(sidePanels);
    mainPanel.add(mainPanels);
    mainPanel.add(chatPanel);

    add(mainPanel, BorderLayout.CENTER);

    try {
      setIconImage(ImageIO.read(new File("images/logo.png")));
    } catch (IOException exc) {
      exc.printStackTrace();
    }

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1000, 600);
    setVisible(true);
    setResizable(false);
    chatField.requestFocus();
  }
  public void actionPerformed(ActionEvent e) {
    Object o = e.getSource();

    for (JRadioButton u : ub) {
      if (o == u) {
        mapTM.setUnitType(u.getText());
        System.out.println("Set unit type - " + u.getText());
        return;
      }
    }

    if (o == timer) {

      /*
      mmLabel.setText("Main Menu ("+(cdTime--)+")");

      if(cdTime == 0){
      	timer.stop();
      	gsButton.setText("Game Start");
      	mmLabel.setText("Main Menu");

      	ArrayList<Building> bArr = new ArrayList<Building>();

      	String temp = "Elixir Collector-24,8-960|Elixir Collector-31,8-960|Gold Mine-17,10-960|Elixir Collector-25,21-960|Elixir Collector-11,22-960";
      	String[] bs = temp.split("\\|");
      	for(String b : bs){
      		String[] bParts = b.split("-");
      		String[] cParts = bParts[1].split(",");
      		int x = Integer.parseInt(cParts[0].trim());
      		int y = Integer.parseInt(cParts[1].trim());

      		Building tb = new Building(bParts[0], new Coordinate(x,y));
      		tb.setHp(Integer.parseInt(bParts[2].trim()));

      		bArr.add(tb);
      	}



      	mapTM.setBuildings(bArr);
      	switchCards("TM");
      }
      */

      return;
    }

    if (o == gsButton) {

      if (timer.isRunning()) {
        // timer.stop();
        gsButton.setText("Game Start");
        mmLabel.setText("Main Menu");
        // sends the leave command
        client.sendUDP("leave~" + unameUDP);
        return;
      }
      // sends the joinlobby command
      client.sendUDP("joinlobby~" + unameUDP);
      // gsButton.setText("Game Stop");
      String serverResp = client.receiveUDP();

      if (serverResp.trim().equals("false")) {

        // place false handler here

      } else {

        String[] enemies = serverResp.trim().split(",");
        ArrayList<Building> bArr = new ArrayList<Building>();
        String mapConfig = getBaseConfig(enemies[0]);
        String[] bs = mapConfig.split("\\|");
        for (String b : bs) {

          String[] bParts = b.split("-");
          String[] cParts = bParts[1].split(",");
          int x = Integer.parseInt(cParts[0].trim());
          int y = Integer.parseInt(cParts[1].trim());

          Building tb = new Building(bParts[0], new Coordinate(x, y));
          tb.setHp(Integer.parseInt(bParts[2].trim()));
          bArr.add(tb);
        }

        mapTM.setBuildings(bArr);
        switchCards("TM");
      }

      // System.out.println(serverResp);
      // cdTime = 10;
      // timer.start();
      return;
    }

    if (o == logout) {
      client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
      chatArea.setText("");

      switchCards("Login");
      return;
    }

    if (o == cmButton) {
      String baseConfig = getBaseConfig();
      System.out.println("base config: " + baseConfig);

      for (int i = 0; i < mapSize; i++) {
        for (int j = 0; j < mapSize; j++) {
          tiles[i][j].setValue("");
        }
      }

      if (!baseConfig.equals("")) {

        String[] bs = baseConfig.split("\\|");
        for (String b : bs) {
          String[] bParts = b.split("-");
          String[] cParts = bParts[1].split(",");
          int x = Integer.parseInt(cParts[0].trim());
          int y = Integer.parseInt(cParts[1].trim());

          int index = 0;
          for (int i = 0; i < bb.size(); i++) {
            if (bb.get(i).getText().split("-")[0].trim().equals(bParts[0])) {
              index = i;
              break;
            }
          }
          insertBuilding(y, x, index);
        }
      }

      switchCards("CM");

      return;
    }

    if (o == tmButton) {

      ArrayList<Building> bArr = new ArrayList<Building>();

      for (int i = 0; i < 40; i++) {
        for (int j = 0; j < 40; j++) {
          if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) {
            continue;
          }
          // weird part here
          bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i)));
        }
      }

      mapTM.setBuildings(bArr);

      switchCards("TM");
      return;
    }

    // if it the who is in button
    if (o == whoIsIn) {
      client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
      return;
    }

    if (o == cmBack) {
      ArrayList<Building> bArr = new ArrayList<Building>();
      for (int i = 0; i < 40; i++) {
        for (int j = 0; j < 40; j++) {
          if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) {
            continue;
          }
          // weird part here
          bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i)));
        }
      }

      String temp = "mapdata~" + unameUDP + "~";
      int tileCount = 40;
      int dim = 600;
      int tileDim = (int) (dim / tileCount);
      int counter = 0;
      for (Building b : bArr) {
        int x, y, hp;
        x = b.getPos().getX() / tileDim;
        y = b.getPos().getY() / tileDim;
        hp = b.getHp();
        temp += b.getName() + "-" + x + "," + y + "-" + hp + "|";
        counter += 1;
      }
      if (counter > 0) {
        temp = temp.substring(0, temp.length() - 1); // removes the last '|'
      } else {
        temp += "none";
      }

      client.sendUDP(temp); // allows saving of the current state of the map into the user's account

      switchCards("Menu");

      return;
    }
    if (o == tmBack) {
      switchCards("Menu");

      return;
    }

    for (int i = 0; i < 40; i++) {
      for (int j = 0; j < 40; j++) {
        if (o == tiles[i][j]) {
          for (int k = 0; k < bb.size(); k++) {
            if (bb.get(k).isSelected()) {
              if (bb.get(k).getText().equals("Remove Building")) {
                removeBuilding(i, j);
                return;
              }

              insertBuilding(i, j, k);
              // JOptionPane.showMessageDialog(null, bb.get(k).getText());
              return;
            }
          }

          // JOptionPane.showMessageDialog(null, "i-"+i+" j-"+j);
          return;
        }
      }
    }

    // ok it is coming from the JTextField
    if (connected) {
      // just have to send the message
      client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, chatField.getText()));
      chatField.setText("");
      return;
    }

    if (o == login) {
      // ok it is a connection request
      String username = usernameField.getText().trim();
      String password = passwordField.getText().trim();
      // empty username ignore it
      if (username.length() == 0) return;
      // empty serverAddress ignore it
      String server = tfServer.getText().trim();
      if (server.length() == 0) return;
      // empty or invalid port numer, ignore it
      String portNumber = tfPort.getText().trim();
      if (portNumber.length() == 0) return;
      int port = 0;
      try {
        port = Integer.parseInt(portNumber);
      } catch (Exception en) {
        return; // nothing I can do if port number is not valid
      }

      // try creating a new Client with GUI
      client = new Client(server, port, username, password, this);
      // test if we can start the Client
      if (!client.start()) return;

      unameUDP = username;

      switchCards("Menu");
      // fetching of the base_config string from the database

      chatField.setText("");
      chatArea.setText("");
    }
  }
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
Example #13
0
  private void initComponents() {
    // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    dialogPane = new JPanel();
    contentPanel = new JPanel();
    panel1 = new JPanel();
    label2 = new JLabel();
    ttfSizeW = new JTextField();
    label4 = new JLabel();
    ttfLongi = new JTextField();
    btnGetMap = new JButton();
    label3 = new JLabel();
    ttfSizeH = new JTextField();
    label5 = new JLabel();
    ttfLati = new JTextField();
    btnQuit = new JButton();
    label1 = new JLabel();
    ttfLicense = new JTextField();
    label6 = new JLabel();
    ttfZoom = new JTextField();
    // ComboBox for Saved Locations
    ttfSave = new JComboBox();
    scrollPane1 = new JScrollPane();
    ttaStatus = new JTextArea();
    panel2 = new JPanel();
    panel3 = new JPanel();
    checkboxRecvStatus = new JCheckBox();
    checkboxSendStatus = new JCheckBox();
    ttfProgressMsg = new JTextField();
    progressBar = new JProgressBar();
    lblProgressStatus = new JLabel();

    // ======== this ========
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setTitle("Google Static Maps");
    setIconImage(null);
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());

    // ======== dialogPane ========
    {
      dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));
      dialogPane.setOpaque(false);
      dialogPane.setLayout(new BorderLayout());

      // ======== contentPanel ========
      {
        contentPanel.setOpaque(false);
        contentPanel.setLayout(
            new TableLayout(
                new double[][] {
                  {TableLayout.FILL},
                  {TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED}
                }));
        ((TableLayout) contentPanel.getLayout()).setHGap(5);
        ((TableLayout) contentPanel.getLayout()).setVGap(5);

        // ======== panel1 ========
        {
          panel1.setOpaque(false);
          panel1.setBorder(
              new CompoundBorder(
                  new TitledBorder("Configure the inputs to Google Static Maps"),
                  Borders.DLU2_BORDER));
          panel1.setLayout(
              new TableLayout(
                  new double[][] {
                    {0.17, 0.17, 0.17, 0.17, 0.05, TableLayout.FILL},
                    {TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED}
                  }));
          ((TableLayout) panel1.getLayout()).setHGap(5);
          ((TableLayout) panel1.getLayout()).setVGap(5);

          // ---- label2 ----
          label2.setText("Size Width");
          label2.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label2,
              new TableLayoutConstraints(
                  0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfSizeW ----
          ttfSizeW.setText("512");
          panel1.add(
              ttfSizeW,
              new TableLayoutConstraints(
                  1, 0, 1, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label4 ----
          label4.setText("Latitude");
          label4.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label4,
              new TableLayoutConstraints(
                  2, 0, 2, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfLongi ----
          ttfLongi.setText("38.931099");
          panel1.add(
              ttfLongi,
              new TableLayoutConstraints(
                  3, 0, 3, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- btnGetMap ----
          btnGetMap.setText("Get Map");
          btnGetMap.setHorizontalAlignment(SwingConstants.LEFT);
          btnGetMap.setMnemonic('G');
          btnGetMap.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  startTaskAction();
                  if (Integer.parseInt(ttfZoom.getText()) < 14) { // coding for zoom values under 14
                    for (int i = 0; i < 14; i++) {
                      if (Integer.parseInt(ttfZoom.getText()) == i) {
                        countThis = 14 - i; // gets difference
                        do {
                          counter = counter * 2; // found out code zooms in powers of 2.
                          pixelX =
                              0.000084525
                                  * counter; // Values per Latitude, trial and error method used to
                                             // find these numbers.
                          pixelY = 0.00006725 * counter; // Values per Longitude
                          counter1++;
                        } while (counter1 != countThis); // loops the amount of differences
                      }
                      counter = 1; // Resetters
                      counter1 = 0;
                    }
                  } else if (Integer.parseInt(ttfZoom.getText())
                      > 14) { // coding for zoom values over 14
                    for (int i = 14; i < 19; i++) {
                      if (Integer.parseInt(ttfZoom.getText()) == i) {
                        countThis = i - 14; // gets difference
                        do {
                          counter = counter * 2;
                          pixelX = 0.000084525 / counter; // Values per Latitude
                          pixelY = 0.00006725 / counter; // Values per Longitude	            	
                          counter1++;
                        } while (counter1 != countThis); // loops amount of differences
                      }
                      counter = 1; // Resetters
                      counter1 = 0;
                    }
                  } else { // coding for zoom default value of 14.
                    pixelX = 0.000084525;
                    pixelY = 0.00006725;
                  }

                  BigDecimal sendPixelX = new BigDecimal(pixelX);
                  BigDecimal sendPixelY = new BigDecimal(pixelY);

                  pixelX =
                      (sendPixelX.setScale(6, BigDecimal.ROUND_HALF_UP))
                          .doubleValue(); // allows for bigger decimal zoom variables
                  pixelY =
                      (sendPixelY.setScale(6, BigDecimal.ROUND_HALF_UP))
                          .doubleValue(); // Won't reach zoom 1-5 without these!
                }
              });
          panel1.add(
              btnGetMap,
              new TableLayoutConstraints(
                  5, 0, 5, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label3 ----
          label3.setText("Size Height");
          label3.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label3,
              new TableLayoutConstraints(
                  0, 1, 0, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfSizeH ----
          ttfSizeH.setText("512");
          panel1.add(
              ttfSizeH,
              new TableLayoutConstraints(
                  1, 1, 1, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label5 ----
          label5.setText("Longitude");
          label5.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label5,
              new TableLayoutConstraints(
                  2, 1, 2, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfLati ----
          ttfLati.setText("-77.3489");
          panel1.add(
              ttfLati,
              new TableLayoutConstraints(
                  3, 1, 3, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- btnQuit ----
          btnQuit.setText("Quit");
          btnQuit.setMnemonic('Q');
          btnQuit.setHorizontalAlignment(SwingConstants.LEFT);
          btnQuit.setHorizontalTextPosition(SwingConstants.RIGHT);
          btnQuit.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  quitProgram();
                }
              });
          panel1.add(
              btnQuit,
              new TableLayoutConstraints(
                  5, 1, 5, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label1 ----
          label1.setText("License Key");
          label1.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label1,
              new TableLayoutConstraints(
                  0, 2, 0, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfLicense ----
          ttfLicense.setToolTipText("Enter your own URI for a file to download in the background");
          panel1.add(
              ttfLicense,
              new TableLayoutConstraints(
                  1, 2, 1, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label6 ----
          label6.setText("Zoom");
          label6.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label6,
              new TableLayoutConstraints(
                  2, 2, 2, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfZoom ----
          ttfZoom.setText("14");
          panel1.add(
              ttfZoom,
              new TableLayoutConstraints(
                  3, 2, 3, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfSave ----
          ttfSave.removeAllItems();
          // JComboBox ttfSave = new JComboBox();
          getSavedLocations(); // grabs a new list
          for (int i = 0; i < loc.size(); i++) // populates this list using a arrayList
          ttfSave.addItem(loc.get(i));

          ttfSave.setSelectedIndex(0);
          panel1.add(
              ttfSave,
              new TableLayoutConstraints(
                  5, 2, 5, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
          // Action Listener to update the coordinates on selected Location
          ttfSave.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  if (mapIsUp == 0) {
                    Object contents = ttfSave.getSelectedItem(); // grabs users selection
                    System.out.println(contents);
                    if (contents != null) {
                      stringCoords = contents.toString();
                      setCoords = stringCoords.split("\\s+");
                      ttfLongi.setText(
                          setCoords[
                              1]); // sets the texts in the longitude and latitude fields to
                                   // coordinates selected
                      ttfLati.setText(setCoords[0]);
                    }
                  }
                }
              });
        }
        contentPanel.add(
            panel1,
            new TableLayoutConstraints(
                0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

        // ======== scrollPane1 ========
        {
          scrollPane1.setBorder(
              new TitledBorder("System.out - displays all status and progress messages, etc."));
          scrollPane1.setOpaque(false);

          // ---- ttaStatus ----
          ttaStatus.setBorder(Borders.createEmptyBorder("1dlu, 1dlu, 1dlu, 1dlu"));
          ttaStatus.setToolTipText(
              "<html>Task progress updates (messages) are displayed here,<br>along with any other output generated by the Task.<html>");
          scrollPane1.setViewportView(ttaStatus);
        }
        contentPanel.add(
            scrollPane1,
            new TableLayoutConstraints(
                0, 1, 0, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

        // ======== panel2 ========
        {
          panel2.setOpaque(false);
          panel2.setBorder(
              new CompoundBorder(
                  new TitledBorder("Status - control progress reporting"), Borders.DLU2_BORDER));
          panel2.setLayout(
              new TableLayout(
                  new double[][] {
                    {0.45, TableLayout.FILL, 0.45},
                    {TableLayout.PREFERRED, TableLayout.PREFERRED}
                  }));
          ((TableLayout) panel2.getLayout()).setHGap(5);
          ((TableLayout) panel2.getLayout()).setVGap(5);

          // ======== panel3 ========
          {
            panel3.setOpaque(false);
            panel3.setLayout(new GridLayout(1, 2));

            // ---- checkboxRecvStatus ----
            checkboxRecvStatus.setText("Enable \"Recieve\"");
            checkboxRecvStatus.setOpaque(false);
            checkboxRecvStatus.setToolTipText("Task will fire \"send\" status updates");
            checkboxRecvStatus.setSelected(true);
            panel3.add(checkboxRecvStatus);

            // ---- checkboxSendStatus ----
            checkboxSendStatus.setText("Enable \"Send\"");
            checkboxSendStatus.setOpaque(false);
            checkboxSendStatus.setToolTipText("Task will fire \"recieve\" status updates");
            panel3.add(checkboxSendStatus);
          }
          panel2.add(
              panel3,
              new TableLayoutConstraints(
                  0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfProgressMsg ----
          ttfProgressMsg.setText("Loading map from Google Static Maps");
          ttfProgressMsg.setToolTipText("Set the task progress message here");
          panel2.add(
              ttfProgressMsg,
              new TableLayoutConstraints(
                  2, 0, 2, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- progressBar ----
          progressBar.setStringPainted(true);
          progressBar.setString("progress %");
          progressBar.setToolTipText("% progress is displayed here");
          panel2.add(
              progressBar,
              new TableLayoutConstraints(
                  0, 1, 0, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- lblProgressStatus ----
          lblProgressStatus.setText("task status listener");
          lblProgressStatus.setHorizontalTextPosition(SwingConstants.LEFT);
          lblProgressStatus.setHorizontalAlignment(SwingConstants.LEFT);
          lblProgressStatus.setToolTipText(
              "Task status messages are displayed here when the task runs");
          panel2.add(
              lblProgressStatus,
              new TableLayoutConstraints(
                  2, 1, 2, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
        }
        contentPanel.add(
            panel2,
            new TableLayoutConstraints(
                0, 2, 0, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
      }
      dialogPane.add(contentPanel, BorderLayout.CENTER);
    }
    contentPane.add(dialogPane, BorderLayout.CENTER);
    setSize(675, 485);
    setLocationRelativeTo(null);
    // JFormDesigner - End of component initialization  //GEN-END:initComponents
  }
Example #14
0
  private void InitUpload() throws ServletException, IOException {
    String sConfig = myUtil.ReadFile(myUtil.getConfigFileRealPath(m_request.getServletPath()));
    ArrayList aStyle = myUtil.getConfigArray("Style", sConfig);

    String sAllowExt, sUploadDir, sBaseUrl, sContentPath;
    String sCurrDir, sDir;
    int nAllowBrowse;
    String sPathShareImage, sPathShareFlash, sPathShareMedia, sPathShareOther;

    // param
    String sType = myUtil.dealNull(m_request.getParameter("type")).toUpperCase();
    String sStyleName = myUtil.dealNull(m_request.getParameter("style"));
    String sCusDir = myUtil.dealNull(m_request.getParameter("cusdir"));
    String sAction = myUtil.dealNull(m_request.getParameter("action")).toUpperCase();

    String s_SKey = myUtil.dealNull(m_request.getParameter("skey"));

    // InitUpload

    String[] aStyleConfig = new String[1];
    boolean bValidStyle = false;

    for (int i = 0; i < aStyle.size(); i++) {
      aStyleConfig = myUtil.split(aStyle.get(i).toString(), "|||");
      if (sStyleName.toLowerCase().equals(aStyleConfig[0].toLowerCase())) {
        bValidStyle = true;
        break;
      }
    }

    if (!bValidStyle) {
      out.print(getOutScript("alert('Invalid Style!')"));
      out.close();
      return;
    }

    if (!aStyleConfig[61].equals("1")) {
      sCusDir = "";
    }

    String ss_FileSize = "",
        ss_FileBrowse = "",
        ss_SpaceSize = "",
        ss_SpacePath = "",
        ss_PathMode = "",
        ss_PathUpload = "",
        ss_PathCusDir = "",
        ss_PathCode = "",
        ss_PathView = "";
    if ((aStyleConfig[61].equals("2")) && (!s_SKey.equals(""))) {
      ss_FileSize =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_FileSize"));
      ss_FileBrowse =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_FileBrowse"));
      ss_SpaceSize =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_SpaceSize"));
      ss_SpacePath =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_SpacePath"));
      ss_PathMode =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_PathMode"));
      ss_PathUpload =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_PathUpload"));
      ss_PathCusDir =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_PathCusDir"));
      ss_PathCode =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_PathCode"));
      ss_PathView =
          (String) myUtil.dealNull(m_session.getAttribute("eWebEditor_" + s_SKey + "_PathView"));

      if (myUtil.IsInt(ss_FileSize)) {
        aStyleConfig[11] = ss_FileSize;
        aStyleConfig[12] = ss_FileSize;
        aStyleConfig[13] = ss_FileSize;
        aStyleConfig[14] = ss_FileSize;
        aStyleConfig[15] = ss_FileSize;
        aStyleConfig[45] = ss_FileSize;
      } else {
        ss_FileSize = "";
      }
      if (ss_FileBrowse.equals("0") || ss_FileBrowse.equals("1")) {
        aStyleConfig[43] = ss_FileBrowse;
      } else {
        ss_FileBrowse = "";
      }
      if (myUtil.IsInt(ss_SpaceSize)) {
        aStyleConfig[78] = ss_SpaceSize;
      } else {
        ss_SpaceSize = "";
      }
      if (!ss_PathMode.equals("")) {
        aStyleConfig[19] = ss_PathMode;
      }
      if (!ss_PathUpload.equals("")) {
        aStyleConfig[3] = ss_PathUpload;
      }
      if (!ss_PathCode.equals("")) {
        aStyleConfig[23] = ss_PathCode;
      }
      if (!ss_PathView.equals("")) {
        aStyleConfig[22] = ss_PathView;
      }

      sCusDir = ss_PathCusDir;
    }

    sBaseUrl = aStyleConfig[19];
    nAllowBrowse = Integer.valueOf(aStyleConfig[43]).intValue();

    if (nAllowBrowse != 1) {
      out.print(getOutScript("alert('Do not allow browse!')"));
      out.close();
      return;
    }

    if (!sCusDir.equals("")) {
      sCusDir = myUtil.replace(sCusDir, "\\", "/");
      if ((sCusDir.startsWith("/"))
          || (sCusDir.startsWith("."))
          || (sCusDir.endsWith("."))
          || (sCusDir.indexOf("./") >= 0)
          || (sCusDir.indexOf("/.") >= 0)
          || (sCusDir.indexOf("//") >= 0)
          || (sCusDir.indexOf("..") >= 0)) {
        sCusDir = "";
      } else {
        if (!sCusDir.endsWith("/")) {
          sCusDir = sCusDir + "/";
        }
      }
    }

    sUploadDir = aStyleConfig[3];
    if (!sBaseUrl.equals("3")) {
      sUploadDir = myUtil.getRealPathFromRelative(m_request.getServletPath(), sUploadDir);
    }
    sUploadDir = GetSlashPath(sUploadDir);
    sUploadDir =
        sUploadDir
            + myUtil.replace(myUtil.replace(sCusDir, "/", sFileSeparator), "\\", sFileSeparator);

    if (sType.equals("FILE")) {
      sAllowExt = aStyleConfig[6];
    } else if (sType.equals("MEDIA")) {
      sAllowExt = aStyleConfig[9];
    } else if (sType.equals("FLASH")) {
      sAllowExt = aStyleConfig[7];
    } else {
      sAllowExt = aStyleConfig[8];
    }

    sPathShareImage =
        GetSlashPath(
            myUtil.getRealPathFromRelative(m_request.getServletPath(), "sharefile/image/"));
    sPathShareFlash =
        GetSlashPath(
            myUtil.getRealPathFromRelative(m_request.getServletPath(), "sharefile/flash/"));
    sPathShareMedia =
        GetSlashPath(
            myUtil.getRealPathFromRelative(m_request.getServletPath(), "sharefile/media/"));
    sPathShareOther =
        GetSlashPath(
            myUtil.getRealPathFromRelative(m_request.getServletPath(), "sharefile/other/"));

    String s_Out = "";
    if (sAction.equals("FILE")) {

      String s_ReturnFlag = myUtil.dealNull(m_request.getParameter("returnflag"));
      String s_FolderType = myUtil.dealNull(m_request.getParameter("foldertype"));
      String s_Dir = myUtil.dealNull(m_request.getParameter("dir"));
      s_Dir = java.net.URLDecoder.decode(s_Dir, "UTF-" + "8");

      String s_CurrDir = "";
      if (s_FolderType.equals("upload")) {
        s_CurrDir = sUploadDir;
      } else if (s_FolderType.equals("shareimage")) {
        sAllowExt = "";
        s_CurrDir = sPathShareImage;
      } else if (s_FolderType.equals("shareflash")) {
        sAllowExt = "";
        s_CurrDir = sPathShareFlash;
      } else if (s_FolderType.equals("sharemedia")) {
        sAllowExt = "";
        s_CurrDir = sPathShareMedia;
      } else {
        s_FolderType = "shareother";
        sAllowExt = "";
        s_CurrDir = sPathShareOther;
      }

      s_Dir = myUtil.replace(s_Dir, "\\", "/");
      if ((s_Dir.startsWith("/"))
          || (s_Dir.startsWith("."))
          || (s_Dir.endsWith("."))
          || (s_Dir.indexOf("./") >= 0)
          || (s_Dir.indexOf("/.") >= 0)
          || (s_Dir.indexOf("//") >= 0)
          || (s_Dir.indexOf("..") >= 0)) {
        s_Dir = "";
      }

      String s_Dir2 = myUtil.replace(s_Dir, "/", sFileSeparator);
      s_Dir2 = myUtil.replace(s_Dir2, "\\", sFileSeparator);

      if (!s_Dir.equals("")) {
        if (CheckValidDir(s_CurrDir + s_Dir2)) {
          s_CurrDir += s_Dir2;
        } else {
          s_Dir = "";
        }
      }

      if (CheckValidDir(s_CurrDir)) {
        File file = new File(s_CurrDir);
        File[] filelist = file.listFiles();
        if (filelist != null && filelist.length > 0) {
          int n = -1;
          for (int i = 0; i < filelist.length; i++) {
            if (filelist[i].isFile()) {
              String s_FileName = filelist[i].getName();
              String s_FileExt = s_FileName.substring(s_FileName.lastIndexOf(".") + 1);
              s_FileExt = s_FileExt.toLowerCase();
              if (CheckValidExt(sAllowExt, s_FileExt)) {
                n++;
                s_Out =
                    s_Out
                        + "arr["
                        + String.valueOf(n)
                        + "]=new Array(\""
                        + s_FileName
                        + "\", \""
                        + String.valueOf(convertFileSize(filelist[i].length()))
                        + "\",\""
                        + formatDate(new Date(filelist[i].lastModified()))
                        + "\");\n";
              }
            }
          }
        }
      }

      s_Out =
          "var arr = new Array();\n"
              + s_Out
              + "parent.setFileList('"
              + s_ReturnFlag
              + "', '"
              + s_FolderType
              + "', '"
              + s_Dir
              + "', arr);";
      out.print(getOutScript(s_Out));

    } else {

      s_Out = "var arrUpload = new Array();\n";
      s_Out += "var arrShareImage = new Array();\n";
      s_Out += "var arrShareFlash = new Array();\n";
      s_Out += "var arrShareMedia = new Array();\n";
      s_Out += "var arrShareOther = new Array();\n";

      s_Out += GetFolderTree(sUploadDir, "Upload", 1, 0).get(0).toString();

      sAllowExt = "";
      if (sType.equals("FILE")) {
        s_Out += GetFolderTree(sPathShareImage, "ShareImage", 1, 0).get(0).toString();
        s_Out += GetFolderTree(sPathShareFlash, "ShareFlash", 1, 0).get(0).toString();
        s_Out += GetFolderTree(sPathShareMedia, "ShareMedia", 1, 0).get(0).toString();
        s_Out += GetFolderTree(sPathShareOther, "ShareOther", 1, 0).get(0).toString();
      } else if (sType.equals("MEDIA")) {
        s_Out += GetFolderTree(sPathShareMedia, "ShareMedia", 1, 0).get(0).toString();
      } else if (sType.equals("FLASH")) {
        s_Out += GetFolderTree(sPathShareFlash, "ShareFlash", 1, 0).get(0).toString();
      } else {
        s_Out += GetFolderTree(sPathShareImage, "ShareImage", 1, 0).get(0).toString();
      }

      s_Out +=
          "parent.setFolderList(arrUpload, arrShareImage, arrShareFlash, arrShareMedia, arrShareOther);";
      out.print(getOutScript(s_Out));
    }
  }