mvn deploy到nexus的snapshots Repository出现Return code is: 400

现象:
settings.xml已经配置好server和mirror,并且ID都为nexus-snapshots
运行:mvn deploy:deploy-file -DgroupId=pentaho-kettle -DartifactId=engine -Dversion=5.4 -Dpackaging=jar -Dfile=C:\git\transformer-core\mcetl\engine\dist\kettle-engine-5.4-SNAPSHOT.jar -Durl=http://url:8081/nexus/content/repositories/snapshots/ -DrepositoryId=nexus-snapshots
报错:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy-file (default-cli) on project standalone-pom: Failed to deploy artifacts: Could not transfer artifact pentaho-kettle:engine:jar:5.4 from/to nexus-snapshots (http://url:8081/nexus/content/repositories/snapshots/): Failed to transfer file: http://url:8081/nexus/content/repositories/snapshots/pentaho-kettle/engine/5.4/engine-5.4.jar. Return code is: 400, ReasonPhrase: Bad Request. -> [Help 1]

解决:
mvn deploy:deploy-file -DgroupId=pentaho-kettle -DartifactId=engine -Dversion=5.4-SNAPSHOT -Dpackaging=jar -Dfile=C:\git\transformer-core\mcetl\engine\dist\kettle-engine-5.4-SNAPSHOT.jar -Durl=http://url:8081/nexus/content/repositories/snapshots/ -DrepositoryId=nexus-snapshots

即上传到snapshots时需要在Dversion上添加-SNAPSHOT

PWC6033: Unable to compile class for JSP的处理

现象:web项目在开发环境下使用jetty运行正常,打包后部署到tomcat上,有部分页面出现HTTP Status 500 - PWC6033: Unable to compile class for JSP报错,重启tomcat部分页面又恢复正常。

解决:项目为maven项目,在pom文件中修改javax.servlet-api依赖,添加<scope>provided</scope>标签,即在打包时不将javax.servlet-api相关包包含。

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

解释:

详情见官方文档描述http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

java.lang.UnsupportedOperationException 异常

报错信息如下:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at Wmic.main(Wmic.java:129)

测试代码:

List list = Arrays.asList("test".split(","));
list.add("test2");

调试发现执行Arrays.asList后的list是java.util.Arrays$ArrayList类型,即是Arrays的一个内部类,其继承自AbstractList,没有override add()等方法,所以会报没有提供该方法的异常,具体可以查看JDK源码。

解决方法:

List list = Arrays.asList("test".split(","));
List arrayList = new ArrayList(list);
arrayList.add("test2");

[Thinking in Java]再读:字符串

1.不可变String

String对象是不可变的,String类中“修改字符串”的方法,实际上都是创建了一个全新的对象。

2.重载“+”与StringBuilder

String只读的特性会带来一定的效率的问题。例如:

public class StringTest {
	public static void main(String[] args) {
		String s = "abc";
		String x = "a" + "b" + s + "c";
	}
}

分析字节码,我们发现编译器并没有傻到一遍一遍的去新建对象:而是自动创建了“StringBuilder”,并每次都调用其append()方法,最后调用toString()将结果存在b中。

反编译 字节码:

D:\workspace\test\src>javap -c StringTest
Compiled from "StringTest.java"
public class StringTest {
public StringTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":
()V
4: return

public static void main(java.lang.String[]);
Code:
0: ldc #2 // String abc
2: astore_1
3: new #3 // class java/lang/StringBuilder
6: dup
7: invokespecial #4 // Method java/lang/StringBuilder."<
init>":()V
10: ldc #5 // String ab
12: invokevirtual #6 // Method java/lang/StringBuilder.ap
pend:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: aload_1
16: invokevirtual #6 // Method java/lang/StringBuilder.ap
pend:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: ldc #7 // String c
21: invokevirtual #6 // Method java/lang/StringBuilder.ap
pend:(Ljava/lang/String;)Ljava/lang/StringBuilder;
24: invokevirtual #8 // Method java/lang/StringBuilder.to
String:()Ljava/lang/String;
27: astore_2
28: return
}

很显然编译器自动用了StringBuilder然后一个个.append();
这么看来我们能随便用String了?不

其实在复杂的字符串拼接中,这个并不可靠,比如循环中用+拼接字符串,可能会创建多个StringBuilder,编译后字节码变得很长,性能也会变差。

这种情形下(在toSring()中使用循环)自己创建StringBuilder是一个好的选择,此外你还可以为其配置大小来避免多次的重新分配缓冲。

陷阱append(a+":"+b) ,这种捷径写法会误导编译器,为新建StringBuilder对象来处理括弧中的字符串操作。

StringBuilder功能丰富:除了常用的append()和toString() 还有insert()\repleace()\subString()\reverse();

StringBuilder是java SE5引入的,在这之前用的是StringBuffer,区别是后者是线程安全的,开销也大一些。

3.无意识的递归
看一下这段代码,运行后将抛出长长的java.lang.StackOverflowError异常。

import java.util.ArrayList;
import java.util.List;

public class InfiniteRecursion {

@Override
public String toString() {
return "InfiniteRecursion address: " + this + "\n";
// return super.toString();
}

public static void main(String[] args) {
List<InfiniteRecursion> v = new ArrayList<InfiniteRecursion>();
for (int i = 0; i < 10; i++)
v.add(new InfiniteRecursion());
System.out.println(v);
}

}

由于在 "InfiniteRecursion address: " + this + "\n"发生了自动类型转换,“+”后面出现的不是String类型,于是编译器将this转换为String,即调用this的toString()方法,于是就发生了递归调用。打印内存地址的正确的用法:super.toString()(即Object.toString())。

4.String上的操作

具体可以参考doc(String)

5.格式化输出

java SE5推出了C语言printf()风格的格式化输出这一功能。

例如:

System.out.printf("Row 1: [%d %f] \n", x, y);

System.out.format("Row 1: [%d %f] \n", x, y);

format()与printf()是等价的.(format是java SE5引入的,可以用于PrintStream或PrintWriter)

 

ant build时“找不到符号”解决方法

今天在对nutch2.x进行测试。第一次,按照官方文档Running Nutch in Eclipse进行ant eclipse,最后build成功。

而后,修改了些pom.xml中的版本号,再进行ant eclipse,出现了失败,于是对pom.xml进行了还原。

再次ant eclipse,出现了很多“找不到符号”,初步估计是存在多个版本的jar造成的

这个问题有一个终极解决方法:删除所有jar包(默认在C:\Users\用户名\.ivy2)

 

使用GNS3模拟三层交换环境进行snmp4j实验

前提

1.下载安装GNS3
2.下载cisco ios镜像,这里使用unzip-c3640-js-mz.124-10.bin(模拟交换机似乎都使用这个的)。

配置GNS3

1.在编辑菜单下的首选项中,可以将语言设置为中文。

2.在编辑菜单下的IOS与Hypervisors中添加IOS,如图所示将unzip-c3640-js-mz.124-10.bin添加进去,其他IOS也可以同样的方法添加进去(注意一个底板有多个IOS时,哪一个设置为默认IOS)。

ios

3.GNS3并不能模拟交换机,我们使用3640添加交换模块进行模拟,二层、三层都用可以进行模拟。为了在拓扑图中区分三层、二层交换,可以在编辑菜单下的标示符管理器中,添加自定义节点。

以下三个图片添加了交换机、三层交换机(都使用3600类型,即配置的3640IOS)、终端节点:

sw
msw
computer

拓扑图连接

这个拓扑是三层交换实现不同VLAN之间的通信的常见实验。R16为三层交换机,R14、R15为二层交换机,底下的三个终端分属两个VLAN中。

最终连接图:

t2

拓扑建立步骤:

1.在左侧的deveices(如下图)选择之前添加的节点放入工作区

t1

2.为3个交换机分别添加模块,都添加NM-16ESW:
(右键交换机 配置)

t3

3.点选左侧的网线图标将交换机连接起来。注意连接终端时可以选择物理网卡、虚拟网卡(请看文章 如何在windows环境下添加虚拟网卡)、NGS3自带的VPCS(选择nio_udp开头的设备),如果不进行snmp4j实验,分别选择不同VPCS即可。我这边三台终端分别连接了一块系统虚拟的网卡(C9)、一块桥接VMware的网卡(C12)、一台VPCS(C13),如下图:

c9
c12
c13

配置交换机

R16三层交换机配置:

#vlan10
R16#vlan database
R16(vlan)#vlan 10
VLAN 10 added:
    Name: VLAN0010
R16(vlan)#exit
APPLY completed.
Exiting....
R16#conf t
Enter configuration commands, one per line.  End with CNTL/Z.
R16(config)#int vlan 10
R16(config-if)#ip address 192.168.1.1 255.255.255.0
R16(config-if)#no sh
R16(config-if)#exit

#vlan20
R16#vlan database
R16(vlan)#vlan 20
VLAN 10 added:
    Name: VLAN0010
R16(vlan)#exit
APPLY completed.
Exiting....
R16#conf t
Enter configuration commands, one per line.  End with CNTL/Z.
R16(config)#int vlan 20
R16(config-if)#ip address 192.168.2.1 255.255.255.0
R16(config-if)#no sh
R16(config-if)#exit

R16(config)#int range f0/0 -1
R16(config-if-range)#switchport trunk encapsulation dot1q
R16(config-if-range)#switchport mode trunk
R16(config-if-range)#
*Mar  1 00:14:12.331: %DTP-5-TRUNKPORTON: Port Fa0/0-1 has become dot1q trunk
*Mar  1 00:14:12.835: %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan10, changed state to up
*Mar  1 00:14:12.839: %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan20, changed state to up
R16(config-if-range)#no sh
R16(config-if-range)#exit
R16(config)#snmp-server community public ro  #设置只读字符串,public为团体名称,ro为只读

R14二层交换机配置:


R14#vlan database
R14(vlan)#vlan 10
VLAN 10 added:
    Name: VLAN0010
R14(vlan)#exit
APPLY completed.
Exiting....
R14#conf t
Enter configuration commands, one per line.  End with CNTL/Z.
#二层交换机关闭routing
R14(config)#no ip routing
R14(config)#int f0/1
R14(config-if)#switchport access vlan 10
R14(config-if)#no sh
R14(config-if)#int f0/0
R14(config-if)#switchport trunk encapsulation dot1q
R14(config-if)#switchport mode trunk
R14(config-if)#
*Mar  1 00:17:19.939: %DTP-5-TRUNKPORTON: Port Fa0/0 has become dot1q trunk
R14(config-if)#no sh

R15二层交换机配置与R14基本一致,区别为R15建立的vlan为20:R15(vlan)#vlan 20

VPCS的配置与测试

打开VPCS

vpcs

如果要设置第一台vpc,在窗口中打入“1”即可(我这里的1是C13这台机器,位于VLAN20中),这里配置好ip网关即可:

vpcs1

然后ping 192.168.1.1和192.168.2.1,通畅即表示整个配置已经成功。

snmp4j实验

[译]Jpcap 教程

Jpcap 教程

1.0 (for Jpcap 0.7)

Author:
    Keita Fujii (kfujii@uci.edu)
Home page:
    http://netresearch.ics.uci.edu/kfujii/jpcap/doc/index.html


目录


介绍

这个文档将会描述如何使用Jpcap开发应用。它会解释 Jpcap中定义的方法和类,当然也会通过展示一些例子来完整的描述怎样去使用Jpcap开发.

这个文档的最新版本可以在这里找到: http://netresearch.ics.uci.edu/kfujii/jpcap/doc/tutorial/index.html

什么是Jpcap

Jpcap是用JAVA捕获和发送数据包的一个开源库。它提供了许多便利:

  • 从线缆中实时捕获原始数据包. 
  • 将捕获的数据包保存为离线文件,并且可以从离线保存的文件中读取数据包.
  • 自动识别数据包类型,并生成相应的Java对象 (for Ethernet, IPv4, IPv6, ARP/RARP, TCP,UDP, and ICMPv4 packets).
  • 在数据包分发到应用之前,据用户指定的规则过滤数据包.
  • 发送原始数据包到网络

jpcap是基于 libpcap/winpcap的, 可以用于在C和Java中实现.

Jpcap 已经在下系统中测试通过:
Microsoft Windows (98/2000/XP/Vista), Linux (Fedora, Ubuntu), Mac OS X (Darwin), FreeBSD, and Solaris.

什么样的应用程序可以使用JPCAP进行开发

JPCAP可用于开发多种网络应用程序,包括(但不限于):

  • 网络和协议分析器
  • 网络监控
  • 流量日志
  • 流量生成器
  • 用户级网桥和路由器
  • 网络入侵检测系统 (NIDS)
  • 网络扫描仪
  • 安全工具

什么是JPCAP不能做的

jpcap的捕获和发送数据包是独立于主机协议的(如TCP / IP)。这意味着,JPCAP不会(也不能)去阻塞、过滤或操纵同一台机器上的其他程序产生的流量:它只是“嗅探”传输在线路上的数据包。因此,它并没有提供如traffic shapers,QoS调度和个人防火墙应用适当的支持.


jpcap的教程:一步步指导使用JPCAP

获得网络接口列表

当你想要从网络中捕获数据包,你首先要做的就是取得你的机器上的网络接口列表.要做到这一点,JPCAP提供 JpcapCaptor.getDeviceList()方法。它返回的NetworkInterface NetworkInterface对象的数组.

一个 NetworkInterface对象包含有关相应的网络接口, 如它的名称,描述,IP和MAC地址,以及datatlink名称和描述的一些信息.

下面的示例代码会获取网络接口列表,并打印出他们的信息.

//获得网络接口列表
NetworkInterface[] devices = JpcapCaptor.getDeviceList();

//遍历网络接口
for (int i = 0; i < devices.length; i++) {
//打印它的名称和描述
System.out.println(i+": "+devices[i].name + "(" + devices[i].description+")");

//打印它的datalink的名称和描述
System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")");

//打印它的MAC地址
System.out.print(" MAC address:");
for (byte b : devices[i].mac_address)
System.out.print(Integer.toHexString(b&0xff) + ":");
System.out.println();

//打印它的IP地址、子网掩码和广播地址
for (NetworkInterfaceAddress a : devices[i].addresses)
System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);
}

此示例代码可能会出现这样的结果如下(在Windows上):

0: \Device\NPF_{C3F5996D-FB82-4311-A205-25B7761897B9}(VMware Virtual Ethernet Adapter)
    data link:EN10MB(Ethernet)
    MAC address:0:50:56:c0:0:1:
    address:/fe80:0:0:0:3451:e274:322a:fd9f null null
    address:/172.16.160.1 /255.255.255.0 /255.255.255.255

或者以下 (on Linux/UNIX):

0 : eth0(null)
    datalink: EN10MB(Ethernet)
MAC address:0:c:29:fb:6c:df:
address:/172.16.32.129 /255.255.255.0 / 172.16.32.255

打开一个网络接口

一旦你获了网络接口列表,并选择了从哪个网络接口来获取数据包,您可以通过使用
using JpcapCaptor.openDevice()方法打开该接口。下面这段代码演示了如何打开一个网络接口.

NetworkInterface[] devices = JpcapCaptor.getDeviceList();
int index=...; // 设置您要打开的接口索引.

//Open an interface with openDevice(NetworkInterface intrface, int snaplen, boolean promics, int to_ms)
JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);

当调用 JpcapCaptor.openDevice()方法时,你可以指定以下参数:
 

Name: Purpose
NetworkInterface intrface 你要打开的网络接口.
int snaplen 一次最多获取bytes.
boolean promics 如果你想在混杂模式(promiscuous mode)下打开网络接口, 否则选择false.

在混杂模式下,你可以从电线中获取每一个数据包,也就是说,即使它的源或目的MAC地址是和你打开的网络接口MAC地址不是一样的.
In在非混杂模式下,您只能捕获你自己主机发送和接收的数据包发.
int to_ms 以毫秒为单位设置一个捕获超时值.

JpcapCaptor.openDevice() 返回JpcapCaptorJpcapCaptor.的一个实例。然后,您可以调用  JpcapCaptor类的几种方法从网络接口捕获数据包.

从网络接口捕获数据包

一旦你获得 JpcapCaptor,的一个实例,就可以从接口捕获数据包.

这里有两种主要的方法使用 JpcapCaptor实例来捕获数据包:使用回调方法,或者一个接一个的捕获数据包.

使用回调方法

在这种方法中,您将实现一个回调方法来处理捕获的数据包,然后将回调方法传递给JPCAP,以便JPCAP每次捕获数据包的时候回调它。让我们来看看做到这一点的方法的细节.

首先,通过定义一个新的class来实现一个回调,它实现了 PacketReceiver接口。该 PacketReceiver接口定义了一个  a receivePacket()方法,所以你需要在类中实现receivePacket()方法.

下面的类实现了 receivePacket()方法 ,该方法简单地打印出所捕获的数据包.

class PacketPrinter implements PacketReceiver {
//这个方法在Jpcap捕获到数据包时都会被调用到
public void receivePacket(Packet packet) {
//仅仅打印出捕获的数据包
System.out.println(packet);
}
}

然后,您可以调用 JpcapCaptor.processPacket()JpcapCaptor.loopPacket() 使用回调方法来启动捕获. 当调用 processPacket() 或 loopPacket()方法, 你也可以指定方法返回之前捕获数据包的数量. 您可以指定-1,无限捕获数据包.

JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);

//call processPacket() to let Jpcap call PacketPrinter.receivePacket() for every packet capture.
captor.processPacket(10,new PacketPrinter());

captor.close();

The two methods for callback, processPacket() and loopPacket(), are very similar. Usually you might want to use processPacket() because it supports timeout and non_blocking mode, while loopPacket() doesn’t.

Capturing
packets one-by-one

Using
a callback method is a little bit tricky because you don’t know when
the callback method is called by Jpcap. If you don’t want to use a
callback method, you can also capture packets using the JpcapCaptor.getPacket() method.

getPacket() method simply returns a captured packet. You can (or have to) call getPacket() method multiple times to capture consecutive packets.

The following sample code also prints out captured packets.

JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);

for(int i=0;i<10;i++){
//capture a single packet and print it out
System.out.println(captor.getPacket());
}

captor.close();

Set capturing filter

In Jpcap, you can set a
filter so that Jpcap doesn’t capture unwanted packets. For example, if
you only want to capture TCP/IPv4 packets, you can set a filter as
following:

JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);
//set a filter to only capture TCP/IPv4 packets
captor.setFilter("ip and tcp", true);

The
filter expression “ip and tcp” means to to “keep only the packets that
are both IPv4 and TCP and deliver them to the application”.

By
properly setting a filter, you can reduce the number of packets to
examine, and thus can improve the performance of your application.

You can check the following homepage for more details about filter expression.

Designing
Capture Filters for Ethereal/Wireshark

Save captured packets
into a file

You
can save captured packets into a binary file so that you can later
retrieve them using Jpcap or other applications which supports reading
a tcpdump format file.

To save captured packets, you first need to open a file by calling JpcapWriter.openDumpFile() method with an instance of JpcapCaptor which was used to capture packets, and a String filename.

JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);
//open a file to save captured packets
JpcapWriter writer=JpcapWriter.openDumpFile(captor,"yourfilename");

Once you obtained an instance of JpcapWriter through openDumpFile() method, you can save captured packets using JpcapWriter.writePacket() method. After you saved all the packets you want to save, you need to call JpcapWriter.close() method to close the opened file.

The following sample code, combined with the above code, captures and saves first 100 packets captured.

for(int i=0;i<10;i++){
//capture a single packet
Packet packet=captor.getPacket();
//save it into the opened file
writer.writePacket(packet);
}
writer.close();

Read saved packets from
a file

In Jpcap, you can read the packets you saved using JpcapWriter by opening the file using JpcapCaptor.openFile() method. Similar to JpcapCaptor.openDevice() method, JpcapCaptor.openFile() method also returns an instance of JpcapCaptor class. So you can use the same ways described in Capture packets from the
network interface
section to read packets from the file. For example, you can read and print out saved packets from a file as follows:

//open a file to read saved packets
JpcapCaptor captor=JpcapCaptor.openFile("yourfilename");

while(true){
//read a packet from the opened file
Packet packet=captor.getPacket();
//if some error occurred or EOF has reached, break the loop
if(packet==null || packet==Packet.EOF) break;
//otherwise, print out the packet
System.out.println(packet);
}

captor.close();

Send packets through a
network interface

You can also send packets to the network using Jpcap.  To send a packet, you need to obtain an instance of JpcapSender by calling either JpcapSender.openDevice() or JpcapCaptor.getJpcapSenderInstance() methods.

Once you obtain an instance of JpcapSender, you can pass an instance of Packet class to JpcapSender.sendPacket() method.

The following sample code sends a TCP/IPv4/Ethernet packet onto a network interface.

//open a network interface to send a packet to
JpcapSender sender=JpcapSender.openDevice(devices[index]);

//create a TCP packet with specified port numbers, flags, and other parameters
TCPPacket p=new TCPPacket(12,34,56,78,false,false,false,false,true,true,true,true,10,10);

//specify IPv4 header parameters
p.setIPv4Parameter(0,false,false,false,0,false,false,false,0,1010101,100,IPPacket.IPPROTO_TCP,
InetAddress.getByName("www.microsoft.com"),InetAddress.getByName("www.google.com"));

//set the data field of the packet
p.data=("data").getBytes();

//create an Ethernet packet (frame)
EthernetPacket ether=new EthernetPacket();
//set frame type as IP
ether.frametype=EthernetPacket.ETHERTYPE_IP;
//set source and destination MAC addresses
ether.src_mac=new byte[]{(byte)0,(byte)1,(byte)2,(byte)3,(byte)4,(byte)5};
ether.dst_mac=new byte[]{(byte)0,(byte)6,(byte)7,(byte)8,(byte)9,(byte)10};

//set the datalink frame of the packet p as ether
p.datalink=ether;

//send the packet p
sender.sendPacket(p);

sender.close();


Jpcap documentation.
Copyright (c) 2007 Keita Fujii. All rights reserved.

Hello Kml JAVA解析kml文件

使用JAVA解析KML 用到Java API for KML这个类库,可以到http://code.google.com/p/javaapiforkml/下载。

除此之外,你可能遇到NoClassDefFoundError的错误,还需要 JAXB这个类库,请到https://jaxb.dev.java.net/下载。

或者你可以查看这个http://labs.micromata.de/display/jak/FAQ帮助文档。

package com.ant;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import de.micromata.opengis.kml.v_2_2_0.Kml;
import de.micromata.opengis.kml.v_2_2_0.Placemark;
import de.micromata.opengis.kml.v_2_2_0.Point;

public class KmlTest {

/*
* 根据name 经度 纬度 生成kml文件
*
*/
public static void getPointKml(String name,double lon, double lat) throws FileNotFoundException {
final Kml kml = new Kml();
kml.createAndSetPlacemark().withName(name)
.withOpen(Boolean.TRUE).createAndSetPoint()
.addToCoordinates(lon, lat);
kml.marshal();
kml.marshal(new File(name+”.kml”));
}

/*
* 解析point的kml文件 打印出经纬度高度
*/
public static void getKmlPoint(String kmlName) {
final Kml kml = Kml.unmarshal(new File(kmlName+”.kml”));
final Placemark placemark = (Placemark) kml.getFeature();
Point point = (Point) placemark.getGeometry();
List coordinates = point.getCoordinates();
for (Coordinate coordinate : coordinates) {
System.out.println(coordinate.getLatitude());
System.out.println(coordinate.getLongitude());
System.out.println(coordinate.getAltitude());
}
}

public static void main(String[] args) throws FileNotFoundException {
//getPointKml(“Hangzhou”,120,30);
getKmlPoint(“Hangzhou”);
}
}
(from 当年的,已经不存在的,我的百度空间)

Ajax的简单实例

这个例子作用是:修正谷歌map在中国的偏移,页面输入真实GPS数据后,通过ajax传回,经过处理后页面无刷新返回偏移后的数据,以便在map中正确定位。

页面,index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>EARTH</title>

<script type=”text/javascript”>
var xmlHttpReq;
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttpReq = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlHttpReq = new ActiveXObject(“Microsoft.XMLHTTP”);
}
}

function sendRequest(url) {
//调用创建XMLHttpReqeust对象的函数
createXMLHttpRequest();
//alert(url);
xmlHttpReq.open(“GET”, url, true);
//调用回调函数(当状态发生改变时调用回调函数)
xmlHttpReq.onreadystatechange = proccessReqeust;
//发送请求
xmlHttpReq.send(null);
}

function proccessReqeust() {
//根据状态
//alert(“当前状态为:” + xmlHttpReq.readyState);
//判断对象状态
if (xmlHttpReq.readyState == 4) {
if (xmlHttpReq.status == 200) {
//以XML接收响应数据
document.getElementById(“offlon”).innerHTML = xmlHttpReq.responseXML
.getElementsByTagName(“offlon”)[0].firstChild.data;

document.getElementById(“offlat”).innerHTML = xmlHttpReq.responseXML
.getElementsByTagName(“offlat”)[0].firstChild.data;

//Add map point
var myLatlng = new google.maps.LatLng(parseFloat( xmlHttpReq.responseXML
.getElementsByTagName(“offlat”)[0].firstChild.data), parseFloat(xmlHttpReq.responseXML
.getElementsByTagName(“offlon”)[0].firstChild.data));
var marker = new google.maps.Marker({
position : myLatlng,
map : map,
title : “Hello World!”
});
//以文本方式接收返回数据
//var respInfomation = xmlHttpReq.responseText;
//alert(respInfomation);
} else {
alert(“响应异常”);
}
}
}

//得到表单信息
function sendInfo() {
var lon = form1.lon.value;
var lat = form1.lat.value;
sendRequest(‘offset?lat=’ + lat + ‘&lon=’ + lon);
}
</script>//以上是Ajax简单的例子

<script
src=”>
<script type=”text/javascript”
src=”http://maps.google.com/maps/api/js?sensor=false“>

</script>
<script>
google.load(“earth”, “1”);
var map;
var ge = null;
var placemark = null;
var geocoder;

function init() {
google.earth.createInstance(“map3d”, initCallback, failureCallback);

var myLatlng = new google.maps.LatLng(30.4419, 120.1419);
var myOptions = {
zoom : 12,
center : myLatlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(“map”), myOptions);
}

function initCallback(object) {
ge = object;
ge.getWindow().setVisibility(true);

ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);

}

function failureCallback(object) {
}

function showBalloon() {
var balloon = ge.createFeatureBalloon(”);
balloon.setFeature(placemark);
balloon.setMinWidth(400);
ge.setBalloon(balloon);
}
function addp() {
var lat = form1.lat.value;
var lon = form1.lon.value;

// Create the placemark.
placemark = ge.createPlacemark(”);
placemark.setName(“TEST”);
placemark.setDescription(‘This is a description’);

// Set the placemark’s location.
var point = ge.createPoint(”);
point.setLatitude(parseFloat(lat));
point.setLongitude(parseFloat(lon));
placemark.setGeometry(point);

// Add the placemark to Earth.
ge.getFeatures().appendChild(placemark);

// Set the FlyTo speed
ge.getOptions().setFlyToSpeed(1);

// Move the camera.
var la = ge.createLookAt(”);
la.set(parseFloat(lat), parseFloat(lon), 0,
ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 20000);
ge.getView().setAbstractView(la);

}

function codeAddress() {
var address = document.getElementById(“address”).value;
geocoder.geocode({
‘address’ : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map : map,
position : results[0].geometry.location
});
} else {
alert(“Geocode was not successful for the following reason: ”
+ status);
}
});
}
</script>//以上调用google API
</head>
<body onload=’init()’ id=’body’>
<form action=”offset” method=”post” name=”form1″>
纬度: <input type=”text” name=”lat” value=”30.278342″ /> 经度: <input
type=”text” name=”lon” value=”120.117099″ /> <input type=”button”
value=”offset” onClick=”sendInfo();addp()” />  <input type=”text”
id=”address” value=”Sydney, NSW” /><input type=”button” value=”解析地址”
onClick=”codeAddress()” /><br> <b> offlat:</b> <span
id=”offlat”></span> <b>offlon:</b> <span id=”offlon”></span>
</form>

<table style=”width: 1200px”>
<tr>
<td style=”width: 50%”>
<div id=’map3d’ style=’border: 1px solid silver; height: 600px;’></div>
</td>
<td style=”width: 50%”>
<div id=”map” style=”border: 1px solid #000; height: 600px;”></div>
</td>
</tr>
</table>
</body>
</html>

 

后台

package com.ant.ser;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Still
* @创建时间:2012-2-16 下午01:33:12
*/
public class OffsetServlet extends HttpServlet {

private static final long serialVersionUID = 6991271447420179202L;

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 设置请求和响应的编码格式
request.setCharacterEncoding("UTF-8");
// 设置响应格式应为XML
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");

PrintWriter out = response.getWriter();
out.println("<respData>");

double lat = Double.valueOf(request.getParameter("lat"));
double lon = Double.valueOf(request.getParameter("lon"));

double lat_p=GoogleTest.latToPixel(lat, 18);//经纬度转像素
double lon_p=GoogleTest.lngToPixel(lon, 18);

Map offsetMap = new HashMap();
offsetMap = TestGoogleOffset.readOffsetData("d:/offset.dat", lon, lat);//此处调用偏移数据,查询偏移像素

double lat_s=GoogleTest.pixelToLat(lat_p+(Integer)offsetMap.get("offY"), 18);//此处将实际像素加上偏移像素再转经纬度
double lon_s=GoogleTest.pixelToLng(lon_p+(Integer)offsetMap.get("offX"), 18);
out.println("<offlat>" + lat_s + "</offlat>");
out.println("<offlon>" + lon_s + "</offlon>");
out.println("</respData>");
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

(from 当年的,已经不存在的,我的百度空间)