7 Sept 2012

Image downloading from web in java code


mport org.w3c.tidy.*;
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import java.util.*;
public class demo
{
public static void main(String arg[])
{
try
{
InputStream input = new URL("http://www.southreels.com").openStream();
Document document = new Tidy().parseDOM(input, null);
NodeList imgs = document.getElementsByTagName("img");
List<String> srcs = new ArrayList<String>();

for (int i = 0; i < imgs.getLength(); i++) {
    srcs.add(imgs.item(i).getAttributes().getNamedItem("src").getNodeValue());
}
int i=0;
for (String src: srcs) {
    System.out.println(i+"  "+src);
i++;
//}
String file =System.getProperty("user.dir")+System.getProperty("file.separator");
URL server = new URL(src);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(file+"demo"+i+".jpg");

    byte[] buffer = new byte[1024];
    int byteReaded = is.read(buffer);
    while(byteReaded != -1)
    {
        os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
    }

   os.close();
}
}
catch(Exception e)
{
}
}
}

How can I load a *.java class file into my java application


You can do it by using classes inside javax.tools. 
You will have a ToolProvider class from which you can obtain a compiler instance and compile code at runtime. 
Later you will load .class files just compiled separately with a ClassLoader unless you obtain directly 
a binary code for the class and you are able to istantiate it directly.



public class SimpleTest
{
  public static void main(String[] args) throws Throwable
  {
    String filename = args[0];
    String className = args[1];
    SimpleCompiler compiler = new SimpleCompiler(filename);
    ClassLoader loader = compiler.getClassLoader();
    Class compClass = loader.loadClass(className);
    Object instance = compClass.newInstance();
  }
}

Downoading PDF from URL in java


                                             
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import com.gnostice.pdfone.PdfDocument;

public class Read_PDF_From_URL {

  public static void main(String[] args) throws IOException {

    URL url1 =
      new URL("http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf");

    byte[] ba1 = new byte[1024];
    int baLength;
    FileOutputStream fos1 = new FileOutputStream("download.pdf");

    try {
      // Contacting the URL
      System.out.print("Connecting to " + url1.toString() + " ... ");
      URLConnection urlConn = url1.openConnection();

      // Checking whether the URL contains a PDF
      if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
          System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
      } else {
        try {

          // Read the PDF from the URL and save to a local file
          InputStream is1 = url1.openStream();
          while ((baLength = is1.read(ba1)) != -1) {
              fos1.write(ba1, 0, baLength);
          }
          fos1.flush();
          fos1.close();
          is1.close();

          // Load the PDF document and display its page count
          System.out.print("DONE.\nProcessing the PDF ... ");
          PdfDocument doc = new PdfDocument();
          try {
            doc.load("download.pdf");
            System.out.println("DONE.\nNumber of pages in the PDF is " +
                               doc.getPageCount());
            doc.close();
          } catch (Exception e) {
            System.out.println("FAILED.\n[" + e.getMessage() + "]");
          }

        } catch (ConnectException ce) {
          System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
        }
      }

    } catch (NullPointerException npe) {
      System.out.println("FAILED.\n[" + npe.getMessage() + "]\n");
    }
  }
}

Downloading jar file in java source code


URL url = new URL("http://...sources.jar");  
InputStream inStream = url.openStream();  
System.out.println(inStream.available());  
BufferedInputStream bufIn = new BufferedInputStream(inStream);  
              
File fileWrite = new File("outputsrc.jar");  
    OutputStream out= new FileOutputStream(fileWrite);  
    BufferedOutputStream bufOut = new BufferedOutputStream(out);  
                    byte buffer[] = new byte[BUFFER_SIZE];  
            while (true) {  
int nRead = bufIn.read(buffer, 0, buffer.length);  
if (nRead <= 0)  
  break;  
bufOut.write(buffer, 0, nRead);  
        }  
              
            bufOut.flush();  
            out.close();  
            inStream.close();

Checking Invalid URL in Java


HttpURLConnection connection = null;
try{         
    URL myurl = new URL("http://www.myURL.com");        
    connection = (HttpURLConnection) myurl.openConnection(); 
    //Set request to header to reduce load.       
    connection.setRequestMethod("HEAD");         
    int code = connection.getResponseCode();        
    System.out.println("" + code); 
} catch {
//Handle invalid URL
}

check if a file exists at url in java


                                             
final URL url = new URL("http://some.where/file.html");
url.openConnection().getResponseCode();

try {
    final URL url = new URL("http://your/url");
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    int responseCode = huc.getResponseCode();
    // Handle response code here...
} catch (UnknownHostException uhe) {
    // Handle exceptions as necessary
} catch (FileNotFoundException fnfe) {
    // Handle exceptions as necessary
} catch (Exception e) {
    // Handle exceptions as necessary
}

Stopwatch in java source code


import java.awt.event.*;
import javax.swing.*;

public class StopWatch2 extends JLabel
            implements KeyListener, ActionListener {

   private long startTime;                           

   private boolean running;  
   private Timer timer;  
   public StopWatch2() {
             super("  Press S  ", JLabel.CENTER);
      addKeyListener(this);
   }

   public void actionPerformed(ActionEvent evt) {

       long time = (System.currentTimeMillis() - startTime) / 1000;
       setText(Long.toString(time));
   }

   public void keyPressed(KeyEvent e) {

          int keyCode=e.getKeyCode();
      if (keyCode==KeyEvent.VK_S) {
                     running = true;
         startTime = e.getWhen(); 
         setText("Running:  0 seconds");
         if (timer == null) {
            timer = new Timer(100,this);
            timer.start();
         }
         else
            timer.restart();
      }
      if(keyCode==KeyEvent.VK_P)
      {

         timer.stop();
         running = false;
         long endTime = e.getWhen();
         double seconds = (endTime - startTime) / 1000.0;
         setText("Time: " + seconds + " sec.");
      }
   }
   public void keyTyped(KeyEvent e)
   {}
   public void keyReleased(KeyEvent e)
   {}

} 


import java.awt.*;
import javax.swing.*;

public class Test2 extends JApplet {

   public void init() {

      StopWatch2 watch = new StopWatch2();
      watch.setFont( new Font("SansSerif", Font.BOLD, 24) );
      watch.setBackground(Color.white);
      watch.setForeground( new Color(180,0,0) );
      watch.setOpaque(true);
      getContentPane().add(watch, BorderLayout.CENTER);

   }

}

keylistener in java


KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher (new MyDispatcher());

You then need to create a key event dispatcher, and add your code into it
   private class MyDispatcher implements KeyEventDispatcher
    {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e)
        {
            if (e.getKeyCode() == 38) //up key
            {
            //Do something when the up key is pressed
            System.out.println("The up key was pressed");
            }
            else if (e.getKeyCode() == 40) //down key
            {
                //Do something when the down key is pressed
                System.out.println("The down key was pressed");
            }
            return false;
        }
    }

How to move the display in java


package Game;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;

@SuppressWarnings("serial")
public abstract class GameCanvas extends Canvas implements Runnable,KeyListener{
 public static final long ONE_SECOND_MILI = 1000;
 protected int frameW;
 protected int frameH;
 protected long fps;
 private long period = 15;
 private BufferStrategy buff;
 private Graphics graph;
 private Color bckGround=(Color.GRAY);
 private Image bckGround_img;
 private Thread t;
 boolean left;
 boolean right;
 boolean up;
 boolean down;
 int lastpressed;
 int newlastpressed;

 private String drawFps = "0";
    public GameCanvas(int w,int h){
        this.frameW=w;
        this.frameH=h;
        this.setIgnoreRepaint(true);
        this.setBounds(0,0,frameW,frameH);
        this.setBackground(Color.GREEN);
        this.setVisible(true);
    }

    public GameCanvas(int w,int h,Color bck){
        this.frameW=w;
        this.frameH=h;
        this.bckGround=bck;
        this.setIgnoreRepaint(true);
        this.setBounds(0,0,frameW,frameH);
        this.setBackground(bckGround);
        this.setVisible(true);
    }

    public void addNotify(){
        super.addNotify();
        this.createBufferStrategy(2);
        this.buff=this.getBufferStrategy();
        requestFocus();
        startGame();
    }
    public void startGame(){
        if (t==null){
            t=new Thread(this);
            t.start();
        }
    }
    public void run(){
        while(true){
            long beginTime=System.currentTimeMillis();
//          try {
//              Thread.sleep(25);
//          } catch (InterruptedException e1) {
//              // TODO Auto-generated catch block
//              e1.printStackTrace();
//          }
            Update();
            Render();
            Draw();
            fps=System.currentTimeMillis() - beginTime ;
            long sleepTime=period-fps;
            if (sleepTime == 30) sleepTime = -1;
            fps= ONE_SECOND_MILI / ((period * 2) - sleepTime);
            try{
                if (sleepTime > 0){
                    Thread.sleep(sleepTime);

                }
            }
            catch(Exception e){
            }
        }
    }
    public void Render(){
        graph = buff.getDrawGraphics();

        if (!HasImgBackground()){
            graph.setColor(bckGround);
            graph.fillRect(0, 0, frameW, frameH);
        }else{
            graph.drawImage(bckGround_img, 0, 0, frameW, frameH,null);
        }
        graph.setColor(new Color(255,255,255));
        graph.drawString("FPS: " + fps , 10, 15);
        Paint(graph);
    }
    private void Draw(){
        if(!buff.contentsLost()){
            buff.show();
            if(graph != null){
                graph.dispose();
            }
        }
    }
    private boolean HasImgBackground(){
        if (bckGround_img==null){
            return false;
        }
        return true;
    }
    public void setBackgroundImg(Image image){
        this.bckGround_img=image;
    }
    public void deleteBackground(){
        this.bckGround_img=null;
    }
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_LEFT){
            left=true;
            if(lastpressed!=4)
                newlastpressed=lastpressed;
            lastpressed=4;
        }
        if(e.getKeyCode()==KeyEvent.VK_UP){
            up=true;
            if(lastpressed!=1)
                newlastpressed=lastpressed;
            lastpressed=1;
        }
        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            right=true;
            if(lastpressed!=2)
                newlastpressed=lastpressed;
            lastpressed=2;
        }
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            down=true;
            if(lastpressed!=3)
                newlastpressed=lastpressed;
            lastpressed=3;
        }

    }
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_LEFT){
            left=false;
            if(up||right||down)
                if(newlastpressed!=0)
                lastpressed=newlastpressed;
        }
        if(e.getKeyCode()==KeyEvent.VK_UP){
            up=false;
            if(left||right||down)
                if(newlastpressed!=0)
                lastpressed=newlastpressed;
        }
        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            right=false;
            if(up||left||down)
                if(newlastpressed!=0)
                lastpressed=newlastpressed;
        }
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            down=false;
            if(up||right||left)
                if(newlastpressed!=0)
                lastpressed=newlastpressed;
        }

    }
    public void keyTyped(KeyEvent e) {
    }
    abstract void Update();
    abstract void Paint(Graphics g);
}


package Game;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;


public class Mainth extends GameCanvas{

    private long timeDown = 0;
//  private StopWatch t = new StopWatch();
    static Collision coll=new Collision();
    Character character=new Character();
    static Image wallImage=ImageLoader.getImg().getImage("data/images/objects/brick_wall.png");
    static Image bushImage=ImageLoader.getImg().getImage("data/images/objects/hedge_ver.png");
    static ArrayList<Image> wallArray=new ArrayList<Image>();
    static ArrayList<Image> wall2Array=new ArrayList<Image>();
    static Sprite wallSprite;
    static Sprite wall2Sprite;
    static IndexCounter devIndex;
    static Dude dev;
    static Wall wall;
    static Wall bush;
    static Wall wall2;
    /**not used*/
    int x=0,y=0;
    static ArrayList objects=new ArrayList<Entity>();
    static ArrayList chars=new ArrayList<Dude>();
    static ArrayList projectiles=new ArrayList<>();

    public static void main(String[] args){
        Mainth Canvas=new Mainth(1500,1000);
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(Canvas);
        frame.pack();
        frame.setSize(750, 400);
        frame.setVisible(true);
        Mainth.chars.add(dev);
        Mainth.objects.add(wall);
        Mainth.objects.add(bush);
        Mainth.objects.add(wall2);
    }
    public Mainth(int w,int h){
        super(w,h);
        this.addKeyListener(this);
        CharacterCreation();
    }
    public void CharacterCreation(){
        wallArray.add(wallImage);
        wall2Array.add(bushImage);
        wallSprite=new Sprite(wallArray,1);
        wall2Sprite=new Sprite(wall2Array,1);
        dev=new Dude(character.LinkStandingDown,character.LinkStandingDown.getID(),100,300);
        devIndex=new IndexCounter(character.LinkWalkingDownArray.size(),3);
        wall=new Wall(wallSprite,1,100,50){};
        bush=new Wall(wall2Sprite,1,185,55){};
        wall2=new Wall(wallSprite,1,100,225){};
        bush.setHardness(1);
    }
    Movement movem=new Movement();
    void Update() {
        movem.movement(dev, character, left, right, up, down, lastpressed, devIndex);
        dev.move();
        coll.objectCollision(chars,objects);
        devIndex.Counter();
    }
    void Paint(Graphics g) {
        bush.Draw(g,0);
        wall.Draw(g,0);
        wall2.Draw(g,0);
        dev.Draw(g,devIndex.getIndex());
        Graphics2D g2d= (Graphics2D) g;
    }
    public void animation(){
        String[] animationSprites=dev.getImgs("walk_down");
        int aniTime=0;
        aniTime++;
    }
    public ArrayList<Entity> exportObjects(){
        return objects;
    }
    public ArrayList<Dude> getMainChar(){
        return chars;
    }
}

void renderFrame(Rectangle frame) {
    for(GameObject go : gameObjects) {
        if(frame.contains(go.getGlobalCoordinates())) {
            Rectangle windowCoordinates = new Rectangle();
            windowCoordinates.x = go.getGlobalCoordinates().x - frame.x;
            windowCoordinates.x = go.getGlobalCoordinates().y - frame.y;
            windowCoordinates.x = go.getGlobalCoordinates().width - frame.width;
            windowCoordinates.x = go.getGlobalCoordinates().height - frame.height;

            go.paint(g2, windowCoordinates);
        }
    }
}

How to download zip file in java


import java.io.*;
import java.net.*;

URL url = new URL("http://blah.com/download.zip");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
IntpuStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream("download.zip");
copy(in, out, 1024);
out.close();


public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
    byte[] buf = new byte[bufferSize];
    int n = input.read(buf);
    while (n >= 0) {
      output.write(buf, 0, bytesRead);
      n = input.read(buf);
    }
    output.flush();
  }