从源码中分析HashMap的get跟put方法

话不多说直接上代码

put

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }


final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

#get

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

        final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

问题所在

对于2个方法的逻辑看的不是很懂虽然大概知道,先通过hash去找,如果找不到一样的hash就新建Entry,如果找到一样的判断key是否也相等,如果相等则覆盖value,如果不想等说明是key不相同但是hash相同,那么生成Entry赋值给父的next。本人的逻辑理解是这样的,但是对源码还是看不懂。
1. ,put方法中

if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }

这段逻辑不是很懂。

2.get方法中

if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);

这一段不是很理解,求解释。越详细越好。在写笔记看到这里突然卡住了,求支招。哈哈哈。

4个回答

  1. if ((tab = table) == null || (n = tab.length) == 0)
    1. n = (tab = resize()).length;
    2. if ((p = tab[i = (n - 1) & hash]) == null)
    3. tab[i] = newNode(hash, key, value, null);
    4. else {
    5. Node e; K k;
    6. if (p.hash == hash &&
    7. ((k = p.key) == key || (key != null && key.equals(k))))
    8. e = p;
    9. else if (p instanceof TreeNode)
    10. e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
    11. else {
    12. for (int binCount = 0; ; ++binCount) {
    13. if ((e = p.next) == null) {
    14. p.next = newNode(hash, key, value, null);
    15. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
    16. treeifyBin(tab, hash);
    17. break;
    18. }
    19. if (e.hash == hash &&
    20. ((k = e.key) == key || (key != null && key.equals(k))))
    21. break;
    22. p = e;
    23. }
    24. } 解读这一段源码:
  2. java1.8中,map的结构是由Node[] + 链表组成的,和之前的主要区别是,链表部分,当超过8个元素会转成TreeNode对象,由TreeBin封装,也就是链表转换为树形结构便于存储和查找。不是线程安全类,但是如果多线程操作会报出ConCurrentxxxException。

下面按行数来说:
1. 如果当前Node[] 为null 或者 Node数组元素个数为0 执行下面一行代码(省略大括号)
2. resize() 方法返回一个扩容后的Node[],扩容的机制为所需容量的两倍,是原有的1.5倍,这个计算是由负载因子 static final float DEFAULT_LOAD_FACTOR = 0.75f; 来决定的(具体的可以看一下resize()方法,如果有困难我们再讨论一次)。 Node数组元素个数n 赋值为扩容后的长度。
4. 「 (n - 1) & hash] 」定位数组下标位置的经典算法,你可以自己写一个main方法来做几个实验。n=16的话,计算结果肯定在0~15之间。p为计算后取到的一个Node节点 判断是否为null (if else 省略大括号)
5. 如果上述判断为true,那么当前节点赋值为一个新建节点 newNode(x,x,x,x); 这个不用说吧。也是一个经典数据结构。
6. 如果4 中判断结果为false,证明当前下标为i的位置存在节点,那么进行下列操作。
7、8、9. 如果当前node节点的hash 和 节点中key属性值 双等或值等(也就是进行新旧值替换),则将当前节点赋值给e。
10、11. 如果当前节点为TreeNode节点,则将当前操作元素添加到TreeNode[]中(图中,单独的hash,key,value都是当前操作元素的值)。
12. 如果上述都不成立,直接执行下列代码(到这步的意思是,不会是覆盖操作,当前节点也不是treeNode,只能是将当前节点拼接在列表末端)。
13-23. 这是一个看似无限循环的算法,这有几个退出点,按顺序来,第一个break,代表找到了列表末端,把当前元素添加到末端即可。第二个break,是找到新旧值覆盖的元素,进行替换。

14行为常规列表遍历。
15行为如果找到最后一个元素了,直接新建元素,将最后一个元素与新元素逻辑关联。
16行 判断当前个数,是否大于或者等于7,如果是,则将列表转化为TreeBin包装类,其实列表转树的界限是8,但是数组下标是从0开始,所以是TREEIFY_THRESHOLD - 1。
17行就是转化方法了。

用有道笔记纯手打!

qq_27156775
私奔Sven 到了第8个,不是让链表过长,这部分是jdk8做的优化,增快查询效率等。其他理解没问题。记住一点,他初始化的size不是16,而是0,也就是{},当有写操作的时候才会赋值16(也就是1<<4),这个你可以看源码来理解。
2 年多之前 回复
StackTc
StackTc 回复私奔Sven: 看了下,我说下我的理解,1:如果数组为空直接赋值 2:如果hash跟key都一样覆盖 3:如果hash值一样key不一样,创建链表。到了第8个的时候由于不让链表过长。就以树的形势存储数据,
2 年多之前 回复
qq_27156775
私奔Sven 这些都是经典,以jdk8为主,7也要看,因为你要知道它什么这么优化和怎么优化的。
2 年多之前 回复
StackTc
StackTc 回复qq_27156775: 晚上我回去看一下1.8源码,再回复你,还有问下,看源码建议看1.7还是1.8?
2 年多之前 回复
qq_27156775
私奔Sven 首先你要知道,jdk8之后,hashmap中,数据结构是Node[]+(链表|树),Node[]肯定是不会改变的了,那什么时候用链表,什么时候是树呢?他们有个临界点,8,这个数字我在回答里也说过,你在源码里也能找到。知道这个8了,我们看下怎么转化的,首先,数组中的一个元素,他是从链表就够开始构造的,也就是说,你连续put相同的(lenght-1)&hash的值,当个数小于8的时候,用的都是链表,也是就是node.next=new Node()形式,当个数大于等8的时候,将链表转化为TreeNode形式,p instenceof NodeTree 就是用来判断,让数组元素,是链表还是树,如果返回时true,那么,当前元素下的结构已经是树,就用树的方式将当前操作的对象加入到树中,反之还是链表,将当前操作的对象,加入到链表末尾,加入完成之后,判断是否需要转化为树结构,判断条件是什么呢,就是那个8.
2 年多之前 回复
StackTc
StackTc 还是不是很理解TreeNode 这玩意,我目前的理解是newNode为增加一个链表数据或者节点,10.11.12行代码 还不是很理解
2 年多之前 回复
qq_27156775
私奔Sven 对的,jdk8还优化了扩容相关的。
2 年多之前 回复
StackTc
StackTc 回复qq_27156775: 这是jdk1.8新加的?我看1.7都是Entry链表形式的
2 年多之前 回复
qq_27156775
私奔Sven 回复StackTc: 我提到过,当链表的size大于8.下标大于等于7的时候就要转换为TreeNode对象进行存储,在map中,它托管给了TreeBin,所以‘p instanceof TreeNode’ 这个就是判断,数组中的这个元素,是链表还是TreeNode存储,或者说结构。如果是TreeNode,直接采用putTreeVal()方法将当前操作的对象插入。有不懂的可以继续问,有错误,欢迎提出
2 年多之前 回复
StackTc
StackTc else if (p instanceof TreeNode) e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
2 年多之前 回复
StackTc
StackTc else if (p instanceof TreeNode) 这句话可以分析一波吗
2 年多之前 回复
qq_27156775
私奔Sven 如有不对,欢迎指出~
2 年多之前 回复

首先你要知道HashMap最基本的原理,就是把要存储的所有键做Hash,映射到一个数组中去。

但是有可能两个甚至更多的键映射到了同一个位置,因此HashMap需要解决的最核心的问题就来了,就是“哈希冲突”。

jdk7及以前的做法比较简单,如果出现哈希冲突,就在出现冲突的数组位置上创建一个链表,存储所有冲突的对象。这样的问题是,如果冲突的对象很多,那么这个链表会很长,会导致HashMap的性能大大下降。

因此在jdk8发布的时候做了一个优化,在冲突较少的时候依然使用链表,冲突较多的时候,就把链表转换成一棵红黑树。

这也就是你在看代码的时候看到的Node(链表节点)和TreeNode(红黑树节点)。

yizishou
yizishou 回复StackTc: 恩,他说的更具体
2 年多之前 回复
StackTc
StackTc 感谢,你说的很正确,但是我还是打算把分给楼上。
2 年多之前 回复

还有哈希表 为什么比数据查找速度快

StackTc
StackTc 回复whb3299065: 谢谢
2 年多之前 回复
whb3299065
whb3299065 if ((p = tab[i = (n - 1) & hash]) == null)看这句其中i = (n - 1) & hash ,就是计算到哈希值对应的位置,可以看到,它并没有对表结构进行遍历,而是通过计算可以直接得到位置在,只有在该位置被其他元素占用后才会遍历查找,效率是O(1)-O(N)之间,大部分都可以在O(1)的复杂度内找到
2 年多之前 回复

还有问下,为什么别人的博客里面写的源码,跟我本地看的不一样,它的简单,我的好复杂。

StackTc
StackTc 回复whb3299065: 好像是的 我mac装的1.8,但是 还是需要去理解。不能说难,就退
2 年多之前 回复
whb3299065
whb3299065 可能是版本问题吧,我记得1.8的Map变化挺大
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Java HashMap的get(),put()算法时间复杂度

Java7和Java8的HashMap的put(),get()方法的时间复杂度是啥?还请从平均,最好,最坏的角度分析。谢谢

Map下写getget(key).toString();出现空指针异常

最近在编写android程序 源码是这样的: child5 = new ArrayList<Map<String, Object>>(); childData5 = new HashMap<String, Object>(); childData5.put("health_person_txt_smoking", person.getFlag_smoking());// 同理 childData5.put("health_person_txt_smokingnum", smokingnum);// 同理 childData5.put("health_person_txt_drink", person.getFlag_drink()); childData5.put("health_person_txt_drinknum", drinknum); childData5.put("health_person_txt_training", person.getFlag_training());// 同理 childData5.put("health_person_txt_trainingnum", trainingnum);// 同理 childData5.put("health_person_txt_sleep", person.getFlag_sleep()); childData5.put("health_person_txt_sleepnum", sleepnum); child5.add(childData5); 在下面直接编写map.get(key).tostring空指针异常。。。 //这样直接写get(key).toString();出现空指针异常该如何编写这段代码 String name=(String)childData1.get(health_person_txt_name).toString(); String sex=(String)childData1.get(health_person_txt_sex).toString(); String birthday_string=(String)childData1.get(health_person_txt_birthday).toString(); String blood=(String)childData1.get(health_person_txt_blood).toString(); String insurance=(String)childData1.get(health_person_txt_insurance).toString(); 正确的编写方式什么???求各位老师帮忙解答

GET请求,请求参数带有特殊符号被转码的问题。

情况是这样的,我要去请求第三方项目的接口获取资源csv文件, 接口地址为: http://127.0.0.1:8080/getDate/?username=admin/password=123456/startTime=2018-11-4_16:00:00/endTime=2018-11-5_16:30:00/res=min/filter={me=127.0.0.1-0}/DT=csv 通过浏览器直接输入该地址可以正常获取csv文件, 但是我通过java RestTemplate 请求改地址时,/password 后面的参数的特殊符号就被转码了,然后就请求不到了, 变成这样: [org.springframework.web.client.RestTemplate] - GET request for "http://127.0.0.1:8080/getDate/?username=admin/password%3D123456/startTime%3D2018-11-05_14:52:08/endTime%3D2018-11-05_14:55:08/res%3Dmin/filter%3D%7Bme%3D127.0.0.1-0%7D/DT%3Dcsv" resulted in 200 (200) 源码: @RequestMapping(value = "query3.html") @ResponseBody public static String query3() { RestTemplate restTemplate = new RestTemplate(); String result = ""; Date date = new Date(); long time = 30*60*100; //30min SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); String startTime = df.format(new Date(date.getTime() - time)); String endTime = df.format(new Date(date.getTime())); String username = "admin"; String password = "123456"; String res= "min"; String filter = "{me=127.0.0.1-0}"; String DT = "csv"; Map<String,String> queryMap = new HashMap<>(); queryMap.put("username",username); queryMap.put("password",password); queryMap.put("startTime",startTime); queryMap.put("endTime",endTime); queryMap.put("res",res); queryMap.put("filter",filter); queryMap.put("DT",DT); String dataUrl = "http://127.0.0.1:8080/getDate/"; String queryMapUrl = "?username={username}/password={password}/startTime={startTime}/endTime={endTime}/res={res}/filter={filter}/DT={DT}"; try { result = restTemplate.getForObject(dataUrl+queryMapUrl,String.class,queryMap); }catch (Exception e){ e.printStackTrace(); } return result; } 这要如何解决 谢谢!

Object obj=null obj和null有区别吗

Object obj=null obj和null有区别吗 参见示例 debug下map.get("c")是null 第一个示例 ``` Map<String,Object> map=new HashMap<>(); map.put("a","b"); if (!String.valueOf(map.get("c")).equals("0")) { System.out.println("ds"); } 成功打印 ``` 第二个示例 ``` if (!String.valueOf(null).equals("0")) { System.out.println("ds"); } 报错 ``` String.valueof源码 ``` public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } ```

跪求各位大侠帮忙解决LDA代码问题,小妹感激不尽!

我在网上找到了yangliuy提供的LDA Gibbs Sampling 的JAVA实现源码,但它是针对英文文档的。我在他的基础上,把英文文档换成已经分词的中文文档,并把停用词换成中文的,但运行时老是有问题。 **LdaGibbsSampling代码如下:** package liuyang.nlp.lda.main; import java.io.File; import java.io.IOException; import java.util.ArrayList; import liuyang.nlp.lda.com.FileUtil; import liuyang.nlp.lda.conf.ConstantConfig; import liuyang.nlp.lda.conf.PathConfig; /**Liu Yang's implementation of Gibbs Sampling of LDA * @author yangliu * @blog http://blog.csdn.net/yangliuy * @mail yangliuyx@gmail.com */ public class LdaGibbsSampling { public static class modelparameters { float alpha = 0.5f; //usual value is 50 / K float beta = 0.1f;//usual value is 0.1 int topicNum = 100; int iteration = 100; int saveStep = 10; int beginSaveIters = 50; } /**Get parameters from configuring file. If the * configuring file has value in it, use the value. * Else the default value in program will be used * @param ldaparameters * @param parameterFile * @return void */ private static void getParametersFromFile(modelparameters ldaparameters, String parameterFile) { // TODO Auto-generated method stub ArrayList<String> paramLines = new ArrayList<String>(); FileUtil.readLines(parameterFile, paramLines); for(String line : paramLines){ String[] lineParts = line.split("\t"); switch(parameters.valueOf(lineParts[0])){ case alpha: ldaparameters.alpha = Float.valueOf(lineParts[1]); break; case beta: ldaparameters.beta = Float.valueOf(lineParts[1]); break; case topicNum: ldaparameters.topicNum = Integer.valueOf(lineParts[1]); break; case iteration: ldaparameters.iteration = Integer.valueOf(lineParts[1]); break; case saveStep: ldaparameters.saveStep = Integer.valueOf(lineParts[1]); break; case beginSaveIters: ldaparameters.beginSaveIters = Integer.valueOf(lineParts[1]); break; } } } public enum parameters{ alpha, beta, topicNum, iteration, saveStep, beginSaveIters; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String originalDocsPath = PathConfig.ldaDocsPath; String resultPath = PathConfig.LdaResultsPath; String parameterFile= ConstantConfig.LDAPARAMETERFILE; modelparameters ldaparameters = new modelparameters(); getParametersFromFile(ldaparameters, parameterFile); Documents docSet = new Documents(); docSet.readDocs(originalDocsPath); System.out.println("wordMap size " + docSet.termToIndexMap.size()); FileUtil.mkdir(new File(resultPath)); LdaModel model = new LdaModel(ldaparameters); System.out.println("1 Initialize the model ..."); model.initializeModel(docSet); System.out.println("2 Learning and Saving the model ..."); model.inferenceModel(docSet); System.out.println("3 Output the final model ..."); model.saveIteratedModel(ldaparameters.iteration, docSet); System.out.println("Done!"); } } **Documents代码如下:** package liuyang.nlp.lda.main; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import liuyang.nlp.lda.com.FileUtil; import liuyang.nlp.lda.com.Stopwords; /**Class for corpus which consists of M documents * @author yangliu * @blog http://blog.csdn.net/yangliuy * @mail yangliuyx@gmail.com */ public class Documents { ArrayList<Document> docs; Map<String, Integer> termToIndexMap; ArrayList<String> indexToTermMap; Map<String,Integer> termCountMap; public Documents(){ docs = new ArrayList<Document>(); termToIndexMap = new HashMap<String, Integer>(); indexToTermMap = new ArrayList<String>(); termCountMap = new HashMap<String, Integer>(); } public void readDocs(String docsPath){ for(File docFile : new File(docsPath).listFiles()){ Document doc = new Document(docFile.getAbsolutePath(), termToIndexMap, indexToTermMap, termCountMap); docs.add(doc); } } public static class Document { private String docName; int[] docWords; public Document(String docName, Map<String, Integer> termToIndexMap, ArrayList<String> indexToTermMap, Map<String, Integer> termCountMap){ this.docName = docName; //Read file and initialize word index array ArrayList<String> docLines = new ArrayList<String>(); ArrayList<String> words = new ArrayList<String>(); FileUtil.readLines(docName, docLines); for(String line : docLines){ FileUtil.tokenizeAndLowerCase(line, words); } //Remove stop words and noise words for(int i = 0; i < words.size(); i++){ if(Stopwords.isStopword(words.get(i)) || isNoiseWord(words.get(i))){ words.remove(i); i--; } } //Transfer word to index this.docWords = new int[words.size()]; for(int i = 0; i < words.size(); i++){ String word = words.get(i); if(!termToIndexMap.containsKey(word)){ int newIndex = termToIndexMap.size(); termToIndexMap.put(word, newIndex); indexToTermMap.add(word); termCountMap.put(word, new Integer(1)); docWords[i] = newIndex; } else { docWords[i] = termToIndexMap.get(word); termCountMap.put(word, termCountMap.get(word) + 1); } } words.clear(); } public boolean isNoiseWord(String string) { // TODO Auto-generated method stub string = string.toLowerCase().trim(); Pattern MY_PATTERN = Pattern.compile(".*[a-zA-Z]+.*"); Matcher m = MY_PATTERN.matcher(string); // filter @xxx and URL if(string.matches(".*www\\..*") || string.matches(".*\\.com.*") || string.matches(".*http:.*") ) return true; if (!m.matches()) { return true; } else return false; } } } **FileUtil代码如下:** package liuyang.nlp.lda.com; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.*; public class FileUtil { public static void readLines(String file, ArrayList<String> lines) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(new File(file))); String line = null; while ((line = reader.readLine()) != null) { lines.add(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void writeLines(String file, HashMap<?, ?> hashMap) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(file))); Set<?> s = hashMap.entrySet(); Iterator<?> it = s.iterator(); while (it.hasNext()) { Map.Entry m = (Map.Entry) it.next(); writer.write(m.getKey() + "\t" + m.getValue() + "\n"); } } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void writeLines(String file, ArrayList<?> counts) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(file))); for (int i = 0; i < counts.size(); i++) { writer.write(counts.get(i) + "\n"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void writeLines(String file, ArrayList<String> uniWordMap, ArrayList<Integer> uniWordMapCounts) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(file))); for (int i = 0; i < uniWordMap.size() || i < uniWordMapCounts.size(); i++) { writer.write(uniWordMap.get(i) + "\t" + uniWordMapCounts.get(i) + "\n"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } @SuppressWarnings("unchecked") public static void writeLinesSorted(String file, ArrayList<?> uniWordMap, ArrayList<?> uniWordMapCounts, int flag) { // flag = 0 decreasing order otherwise increasing HashMap map = new HashMap(); if (uniWordMap.size() != uniWordMapCounts.size()) { System.err.println("Array sizes are not equal!!! Function returned."); } else { for (int i = 0; i < uniWordMap.size(); i++) { map.put(uniWordMap.get(i), uniWordMapCounts.get(i)); } map = (HashMap<String, Integer>) ComUtil.sortByValue(map, flag); writeLines(file, map); map.clear(); } } public static void tokenize(String line, ArrayList<String> tokens) { StringTokenizer strTok = new StringTokenizer(line); while (strTok.hasMoreTokens()) { String token = strTok.nextToken(); tokens.add(token); } } public static void print(ArrayList<?> tokens) { for (int i = 0; i < tokens.size(); i++) { System.out.print(tokens.get(i) + " "); } System.out.print("\n"); } // HashMap Operations public static void printHash(HashMap<String, Integer> hashMap) { Set<?> s = hashMap.entrySet(); Iterator<?> it = s.iterator(); while (it.hasNext()) { Map.Entry m = (Map.Entry) it.next(); System.out.println(m.getKey() + "\t" + m.getValue()); } } public static ArrayList<String> getHashMap(HashMap<?, ?> hm) { ArrayList<String> a = new ArrayList<String>(); Set<?> s = hm.entrySet(); Iterator<?> it = s.iterator(); while (it.hasNext()) { Map.Entry m = (Map.Entry) it.next(); a.add(m.getKey() + "\t" + m.getValue()); } return a; } public static String getKeysFromValue(HashMap<Integer, String> hm, String value) { Set<?> s = hm.entrySet(); // Move next key and value of HashMap by iterator Iterator<?> it = s.iterator(); while (it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m = (Map.Entry) it.next(); if (m.getValue().equals(value)) return m.getKey() + ""; } System.err.println("Error, can't find the data in Hashmap!"); return null; } public static void readHash(String type_map, HashMap<String, String> typeMap) { ArrayList<String> types = new ArrayList<String>(); ArrayList<String> tokens = new ArrayList<String>(); if (type_map != null) { readLines(type_map, types); for (int i = 0; i < types.size(); i++) { if (!types.get(i).isEmpty()) { FileUtil.tokenize(types.get(i), tokens); if (tokens.size() != 0) { if (tokens.size() != 2) { for (int j = 0; j < tokens.size(); j++) { System.out.print(tokens.get(j) + " "); } System.err .println(type_map + " Error ! Not two elements in one line !"); return; } if (!typeMap.containsKey(tokens.get(0))) typeMap.put(tokens.get(0), tokens.get(1)); else { System.out.println(tokens.get(0) + " " + tokens.get(1)); System.err.println(type_map + " Error ! Same type in first column !"); return; } } tokens.clear(); } } } } public static void readHash2(String type_map, HashMap<String, Integer> hashMap) { ArrayList<String> types = new ArrayList<String>(); ArrayList<String> tokens = new ArrayList<String>(); if (type_map != null) { readLines(type_map, types); for (int i = 0; i < types.size(); i++) { if (!types.get(i).isEmpty()) { FileUtil.tokenize(types.get(i), tokens); if (tokens.size() != 0) { if (tokens.size() != 2) { for (int j = 0; j < tokens.size(); j++) { System.out.print(tokens.get(j) + " "); } System.err .println(type_map + " Error ! Not two elements in one line !"); return; } if (!hashMap.containsKey(tokens.get(0))) hashMap.put(tokens.get(0), new Integer(tokens.get(1))); else { System.out.println(tokens.get(0) + " " + tokens.get(1)); System.err.println(type_map + " Error ! Same type in first column !"); return; } } tokens.clear(); } } } } public static void readHash3(String type_map, HashMap<String, Integer> hashMap) { ArrayList<String> types = new ArrayList<String>(); ArrayList<String> tokens = new ArrayList<String>(); if (type_map != null) { readLines(type_map, types); for (int i = 0; i < types.size(); i++) { if (!types.get(i).isEmpty()) { FileUtil.tokenize(types.get(i), tokens); if (tokens.size() != 0) { if (tokens.size() < 2) { for (int j = 0; j < tokens.size(); j++) { System.out.print(tokens.get(j) + " "); } System.err .println(type_map + " Error ! Not two elements in one line !"); return; } String key = tokens.get(0); String value = tokens.get(tokens.size() - 1); for (int no = 1; no < tokens.size() - 1; no++) { key += " " + tokens.get(no); } if (!hashMap.containsKey(key)) hashMap.put(key, new Integer(value)); else { System.out.println(key + " " + value); System.err.println(type_map + " Error ! Same type in first column !"); return; } } tokens.clear(); } } } } /** * Create a directory by calling mkdir(); * * @param dirFile */ public static void mkdir(File dirFile) { try { // File dirFile = new File(mkdirName); boolean bFile = dirFile.exists(); if (bFile == true) { System.err.println("The folder exists."); } else { System.err .println("The folder do not exist,now trying to create a one..."); bFile = dirFile.mkdir(); if (bFile == true) { System.out.println("Create successfully!"); } else { System.err .println("Disable to make the folder,please check the disk is full or not."); } } } catch (Exception err) { System.err.println("ELS - Chart : unexpected error"); err.printStackTrace(); } } public static void mkdir(File file, boolean b) { if(b) {// true delete first deleteDirectory(file); mkdir(file); } else { mkdir(file); } } /** * * @param path * @return */ static public boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } /** * List files in a given directory * * */ static public String[] listFiles(String inputdir) { File dir = new File(inputdir); String[] children = dir.list(); if (children == null) { // Either dir does not exist or is not a directory } else { for (int i = 0; i < children.length; i++) { // Get filename of file or directory String filename = children[i]; } } return children; } /** * List files in a given directory * * */ static public String[] listFilteredFiles(String inputdir, final String filterCondition) { File dir = new File(inputdir); String[] children = dir.list(); // It is also possible to filter the list of returned files. // This example does not return any files that start with `.'. FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(filterCondition); } }; children = dir.list(filter); return children; } /** * List files recursively in a given directory * * */ static public void listFilesR() { File dir = new File("directoryName"); String[] children = dir.list(); // The list of files can also be retrieved as File objects File[] files = dir.listFiles(); // This filter only returns directories FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; files = dir.listFiles(fileFilter); } /** * Frequently used functions * */ static public int count(String a, String contains) { int i = 0; int count = 0; while (a.contains(contains)) { i = a.indexOf(contains); a = a.substring(0, i) + a.substring(i + contains.length(), a.length()); count++; } return count; } public static void print(String[] files) { for (int i = 0; i < files.length; i++) { System.out.print(files[i] + " "); } System.out.print("\n"); } public static void print(int[] c1) { for (int i = 0; i < c1.length; i++) { System.out.print(c1[i] + " "); } System.out.println(); } public static void test() { String a = "fdsfdsaf"; a += "\nfdsaf fd fd"; a += "\nfd sf fd fd\n"; System.out.println(a); a = a.replaceAll("\n+", " "); System.out.println(a); System.exit(0); } public static void readHash(String type_map, HashMap<String, String> typeMap, boolean flag) { ArrayList<String> types = new ArrayList<String>(); ArrayList<String> tokens = new ArrayList<String>(); if(type_map != null) { readLines(type_map, types); for (int i = 0; i < types.size(); i++) { if (!types.get(i).isEmpty()) { FileUtil.tokenize(types.get(i), tokens); if(tokens.size() != 0) { if (tokens.size() != 2) { for(int j = 0; j < tokens.size(); j++) { System.out.print(tokens.get(j)+" "); } System.err .println(type_map + " Error ! Not two elements in one line !"); return; } String tokens0 = ""; String tokens1 = ""; if(flag) { tokens0 = tokens.get(0).trim(); tokens1 = tokens.get(1).trim(); } else { tokens0 = tokens.get(1).trim(); tokens1 = tokens.get(0).trim(); } if (!typeMap.containsKey(tokens0)) typeMap.put(tokens0, tokens1); else { System.err.println(tokens0 + " " + tokens1); System.err .println(type_map + " Ignore this one ! Same type in first column !"); } } tokens.clear(); } } } } public static String filter4tokenization(String inputstring) { // inputstring = "fds fds Won't won't can't Can't ain't"; // aggregate common tokenization error inputstring = inputstring.replaceAll("(?i)won't", "will not"); inputstring = inputstring.replaceAll("(?i)can't", "can not"); inputstring = inputstring.replaceAll("(?i)shan't", "shall not"); inputstring = inputstring.replaceAll("(?i)ain't", "am not"); return inputstring; } public static void tokenizeAndLowerCase(String line, ArrayList<String> tokens) { // TODO Auto-generated method stub StringTokenizer strTok = new StringTokenizer(line); while (strTok.hasMoreTokens()) { String token = strTok.nextToken(); tokens.add(token.toLowerCase().trim()); } } } 运行结果显示:The folder exists. wordMap size 0 1 Initialize the model ... 2 Learning and Saving the model ... Iteration 0 Iteration 1 Iteration 2 Saving model at iteration 80 ... Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) at liuyang.nlp.lda.main.LdaModel.saveIteratedModel(LdaModel.java:228) at liuyang.nlp.lda.main.LdaModel.inferenceModel(LdaModel.java:102) at liuyang.nlp.lda.main.LdaGibbsSampling.main(LdaGibbsSampling.java:89)。 请问是什么原因呢?

kindeditor成功上传图片后,在富文本框内无法正常显示

我直接下载的demo,用servlet改写了jsp,没有问题,但是现在用springboot,就出现了这种问题。 不废话,直接上代码,恳请各位大神的指导: html: ``` <link rel="stylesheet" href="/kindeditor-master/themes/default/default.css" /> <link rel="stylesheet" href="/kindeditor-master/plugins/code/prettify.css" /> <script charset="utf-8" src="/kindeditor-master/kindeditor-all.js"></script> <script charset="utf-8" src="/kindeditor-master/lang/zh-CN.js"></script> <script charset="utf-8" src="/kindeditor-master/plugins/code/prettify.js"></script> <script> KindEditor.ready(function(K) { K.create('textarea[name="content1"]', { cssPath : '/kindeditor-master/plugins/code/prettify.css', uploadJson : '/kindEditor/upLoad', fileManagerJson : '/kindEditor/Manager', allowFileManager : true,//是否允许浏览服务器上传文件 //resizeType : 0,是否可改变编辑器大小0不可以,1可改高度,2都可以。默认为2 afterCreate : function(msg) { var self = this; K.ctrl(document, 13, function() { self.sync(); document.forms['example'].submit(); }); K.ctrl(self.edit.doc, 13, function() { self.sync(); document.forms['example'].submit(); }); } }); prettyPrint(); }); </script> ``` 这是文件上传类: ``` @Controller @RequestMapping("/kindEditor") public class UpLoadJsonAction { @RequestMapping("/upLoad") public void upLoadImage(HttpServletRequest request, HttpServletResponse response){ try { PrintWriter out = response.getWriter(); //文件保存目录路径 String savePath = request.getRealPath("/") + "attached/"; //文件保存目录URL String saveUrl = request.getContextPath() + "/attached/"; //定义允许上传的文件扩展名 HashMap<String, String> extMap = new HashMap<String, String>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //最大文件大小 long maxSize = 1000000; response.setContentType("text/html; charset=UTF-8"); if(!ServletFileUpload.isMultipartContent(request)){ out.println(getError("请选择文件。")); return; } //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ out.println(getError("上传目录不存在。")); return; } //检查目录写权限 if(!uploadDir.canWrite()){ out.println(getError("上传目录没有写权限。")); return; } String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image"; } if(!extMap.containsKey(dirName)){ out.println(getError("目录名不正确。")); return; } //创建文件夹 savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //创建一个DiskFileItemFactory工厂 FileItemFactory factory = new DiskFileItemFactory(); //创建一个文件上传解析器 ServletFileUpload upload = new ServletFileUpload(factory); //设置编码 upload.setHeaderEncoding("UTF-8"); // //判断提交上来的数据是否是上传表单的数据 // if(!ServletFileUpload.isMultipartContent(request)){ // //按照传统方式获取数据 // return; // } //判断提交上来的是list数据 // List items = upload.parseRequest(request); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator item = multipartRequest.getFileNames(); // Iterator itr = items.iterator(); while (item.hasNext()) { String fileName = (String) item.next(); MultipartFile file = multipartRequest.getFile(fileName); // 检查文件大小 if (file.getSize() > maxSize) { out.println(getError("上传文件大小超过限制。")); return; } // 检查扩展名 String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase(); if (!Arrays. asList(extMap.get(dirName).split(",")).contains(fileExt)) { out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。")); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try { File uploadedFile = new File(savePath, newFileName); ByteStreams.copy(file.getInputStream(), new FileOutputStream(uploadedFile)); } catch (Exception e) { } JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); out.println(obj.toJSONString()); } } catch (Exception e) { e.printStackTrace(); } } //上传报错的提示方法 private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); } } ``` 这是文件管理类: ``` @Controller @RequestMapping("/kindEditor") public class FileManagerJsonAction { @RequestMapping("/Manager") public void fileManager(HttpServletRequest request, HttpServletResponse response){ PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //根目录路径 String rootPath = request.getRealPath("/") + "attached/"; //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/ String rootUrl = request.getContextPath() + "/attached/"; //图片扩展名 String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"}; //要打开的文件夹 String dirName = request.getParameter("dir"); if (dirName != null) { if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)){ out.println("无效的目录"); return; } rootPath += dirName + "/"; rootUrl += dirName + "/"; File saveDirFile = new File(rootPath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } } //根据path参数,设置各路径和URL String path = request.getParameter("path") != null ? request.getParameter("path") : ""; String currentPath = rootPath + path; String currentUrl = rootUrl + path; String currentDirPath = path; String moveupDirPath = ""; if (!"".equals(path)) { String str = currentDirPath.substring(0, currentDirPath.length() - 1); moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : ""; } //排序形式,name or size or type String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name"; //不允许使用..移动到上一级目录 if (path.indexOf("..") >= 0) { out.println("Access is not allowed."); return; } //最后一个字符不是/ if (!"".equals(path) && !path.endsWith("/")) { out.println("Parameter is not valid."); return; } //目录不存在或不是目录 File currentPathFile = new File(currentPath); if(!currentPathFile.isDirectory()){ out.println("Directory does not exist."); return; } //遍历目录取的文件信息 List<Hashtable> fileList = new ArrayList<Hashtable>(); if(currentPathFile.listFiles() != null) { for (File file : currentPathFile.listFiles()) { Hashtable<String, Object> hash = new Hashtable<String, Object>(); String fileName = file.getName(); if(file.isDirectory()) { hash.put("is_dir", true); hash.put("has_file", (file.listFiles() != null)); hash.put("filesize", 0L); hash.put("is_photo", false); hash.put("filetype", ""); } else if(file.isFile()){ String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); hash.put("is_dir", false); hash.put("has_file", false); hash.put("filesize", file.length()); hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt)); hash.put("filetype", fileExt); } hash.put("filename", fileName); hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified())); fileList.add(hash); } } if ("size".equals(order)) { Collections.sort(fileList, new SizeComparator()); } else if ("type".equals(order)) { Collections.sort(fileList, new TypeComparator()); } else { Collections.sort(fileList, new NameComparator()); } JSONObject result = new JSONObject(); result.put("moveup_dir_path", moveupDirPath); result.put("current_dir_path", currentDirPath); result.put("current_url", currentUrl); result.put("total_count", fileList.size()); result.put("file_list", fileList); response.setContentType("application/json; charset=UTF-8"); out.println(result.toJSONString()); } } ``` 正常的效果应该是上传完图片后在富文本框内也是正常显示图片。现在可以上传,但是富文本框内的图片无法正常显示。在文件管理里面,可以找到相应的文件夹或者图片,但是图片也无法正常显示。 结果如下: ![图片说明](https://img-ask.csdn.net/upload/201702/28/1488263695_341596.png) ![图片说明](https://img-ask.csdn.net/upload/201702/28/1488263482_296738.png)

JAVA jsoup解析网页时,并以列表方式输出,但采用键值对方式时出现错误,跪求解决!!!!

部分代码:public static List<Map<String, String>> getKcList(String str) { List<Map<String, String>> kcList = new ArrayList<Map<String, String>>(); Document doc = Jsoup.parse(str); Elements datas = doc.getElementsByTag("table"); Element data = datas.get(0); Elements trs = data.getElementsByTag("tr"); for (int i = 0; i < trs.size(); i++) { Elements tds = trs.get(i).select("td[rowspan=2]"); for (int j = 0; j < tds.size(); j++) { if (!"".equals(tds.get(j).text())) { kcList.add(getkcMap(tds.get(j).text())); } } } Log.i("Td","kcList"+kcList.size()); // Log.i("Th","kcList"+kcList.size()); return kcList; } /*************************** * 数据封装 ****************************/ private static Map<String,String>getkcMap(String str){ String courseInfo[]=new String[]{ "课程编号:","课程名称:","教师号:","教师姓名:", "上课时间:", "上课教室:","答疑时间:","答疑地点:", }; String sCourse[] = str.split("\n"); int i = 0; Map<String, String> map = new HashMap<String, String>(); for (;i < sCourse.length; i++) { String s = sCourse[i]; map.put(courseInfo[i], s); Log.i("Td", i + courseInfo[i] + "==" + s); } return map; } } 显示时: private void toShow(){ StringBuffer sb = new StringBuffer(); for(Map<String,String>map:kcList){ for(String key : map.keySet()) { if(!"".equals(map.get(key))) sb.append(key).append(" ").append(map.get(key)).append(" "); } sb.append("\n----------------------\n"); } kb.setText(sb.toString()); } } 显示结果出现错误如下:![图片说明](https://img-ask.csdn.net/upload/201505/30/1432987078_142382.png)

list在debug模式下按一次F6就加入一次是怎么回事?

<1>事情的起因是我在一个Data.txt文件里有如下数据: ![图片说明](https://img-ask.csdn.net/upload/201612/30/1483058910_827050.png) <2>这是我在main里的代码: GetLatAndLngByBaidu b = new GetLatAndLngByBaidu(""); List<String> list = MockUtil.read("D:\\Data\\gongshang.txt"); // for (String string : list) { // try { // System.out.println(string + ":" + b.getByName(string)); // } catch (Exception e) { // e.printStackTrace(); // } // } // 将经度纬度写入到文件里面 File file = new File("D:\\Data\\aaa.txt"); OutputStream ot = null; Map<String, List> map = new HashMap<String, List>(); ot = new FileOutputStream(file, true); byte[] by = null; for (int i = 0; i < list.size(); i++) { String string = list.get(i); string = string.replaceAll(",", "\r\n,"); String[] str = string.split(","); List<String> listId = null; List<String> listNa = null; List<String> listlatlng = null; if (map.get("1") == null) { // listId = new Vector<String>(); listId = new ArrayList<String>(); } listId.add(str[0]); map.put("1", listId); if (map.get("2") == null) { listNa = new ArrayList<String>(); } listNa.add(str[1]); map.put("2", listNa); if (map.get("3") == null) { listlatlng = new ArrayList<String>(); } listlatlng.add(str[2]); map.put("3", listlatlng); for (int j = 0; j < 3; j++) { for (String string2 : (ArrayList<String>) map.get((j + 1) + "")) { by = string2.getBytes(); ot.write(by, 0, by.length); ot.flush(); } } } if (ot != null) { ot.close(); } } ---------------我是分割线----------------------------------------------------------- <3>然后就报错了: ![图片说明](https://img-ask.csdn.net/upload/201612/30/1483059288_111618.png) <4>我在debug下调试: ![图片说明](https://img-ask.csdn.net/upload/201612/30/1483059514_873608.png) <5>后面的就是按一次F6他就加一次: ![图片说明](https://img-ask.csdn.net/upload/201612/30/1483059911_437594.png) <6>我试过向量了,没有用。还有就是可以成功写道我要写入的aaa.txt里: ![图片说明](https://img-ask.csdn.net/upload/201612/30/1483060070_265990.png)

大四安卓学习mars播放器Listview的问题

抱歉麻烦各位了,本人大四狗,目前在看安卓开发,学习mars老师的音乐播放器时遇到了 个问题,就是设置了SimpleAdapter之后仍然无法显示歌名的内容,只显示了个空白的 TEXTVIEW,我研究了无数次依旧没有发现问题在哪,因此来求教各位大神 附上全部代码,没有错误信息,就是显示不出来,每一步调试过确定都有值 代码如下 ``` package com.example.android_mp3; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import com.download.HttpDownloader; import com.model.Mp3Info; import com.xml.Mp3ListContentHandler; import android.app.ListActivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends ListActivity { private static final int UPDATE = 1; private static final int ABOUT = 2; private List<Mp3Info> mp3Infos = null; /* * 用户点击menu按钮后调用,可加入自己的按钮控件 */ @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO 自动生成的方法存根 // 组id,物品id,排序,显示内容 menu.add(0, UPDATE, 1, R.string.mp3list_update); menu.addSubMenu(0, ABOUT, 2, R.string.mp3list_about); return super.onCreateOptionsMenu(menu); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(r).start(); // updateListView(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == UPDATE) { } else if (item.getItemId() == ABOUT) { System.out.println("1"); // updateListView(); } return super.onOptionsItemSelected(item); } // public void updateListView() { // new Thread(new Runnable() { // // @Override // public void run() { // // TODO 自动生成的方法存根 // String xml = downloadXML("http://192.168.88.100:8080/mp3/resources.xml"); // System.out.println("XML------>"); // System.out.println(xml); // System.out.println(Thread.currentThread().getName()); // mp3Infos = parse(xml); // Message msg = Message.obtain(); // msg.sendToTarget(); // } // }) .start(); // List<HashMap<String, String>> list = new ArrayList<HashMap<String, // String>>(); // for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) { // Mp3Info mp3Info = (Mp3Info) iterator.next(); // HashMap<String, String> map = new HashMap<String, String>(); // map.put("mp3_name", mp3Info.getMp3Name()); // map.put("mp3_size", mp3Info.getMp3Size()); // list.add(map); // } // SimpleAdapter adapter = new SimpleAdapter(this, list, // R.layout.mp3info_xml, new String[] { "mp3_name", "mp3_size" }, // new int[] { R.id.mp3_name, R.id.mp3_size }); // setListAdapter(adapter); // } private Handler handler = new Handler() { public void handleMessage(Message msg) { // 显示列表 showList(); } }; Runnable r = new Runnable() { public void run() { String xml = downloadXML("http://192.168.88.100:8080/mp3/resources.xml"); System.out.println("XML------>"); System.out.println(xml); // 解析下载的XML文件 mp3Infos = parse(xml); Message msg = handler.obtainMessage(); msg.sendToTarget(); } }; public void showList() { List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) { Mp3Info mp3Info = (Mp3Info) iterator.next(); HashMap<String, String> map = new HashMap<String, String>(); map.put("mp3_name", mp3Info.getMp3Name()); map.put("mp3_size", mp3Info.getMp3Size()); list.add(map); } SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, list, R.layout.mp3info_xml, new String[] { "mp3Name", "mp3Size" }, new int[] { R.id.mp3_name, R.id.mp3_size }); setListAdapter(simpleAdapter); } private String downloadXML(String urlString) { HttpDownloader httpDownloader = new HttpDownloader(); String result = httpDownloader.download(urlString); return result; } private List<Mp3Info> parse(String xmlStr) { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); List<Mp3Info> infos = new ArrayList<Mp3Info>(); try { XMLReader xmlReader = saxParserFactory.newSAXParser() .getXMLReader(); Mp3ListContentHandler mp3ListContentHandler = new Mp3ListContentHandler( infos); xmlReader.setContentHandler(mp3ListContentHandler); xmlReader.parse(new InputSource(new StringReader(xmlStr))); for (Iterator iterator = infos.iterator(); iterator.hasNext();) { Mp3Info mp3Info = (Mp3Info) iterator.next(); System.out.println(mp3Info); } } catch (SAXException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return infos; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // Mp3Info mp3Info = mp3Infos.get(position); // System.out.println("----->mp3info" + mp3Info); super.onListItemClick(l, v, position, id); } } ``` xml的 ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="1dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:paddingTop="1dip"> <TextView android:id="@+id/mp3_name" android:layout_width="180dip" android:layout_height="30dip" android:textSize="10pt" /> <TextView android:id="@+id/mp3_size" android:layout_width="180dip" android:layout_height="30dip" android:textSize="10pt" /> </LinearLayout> ``` ![图片说明](https://img-ask.csdn.net/upload/201512/11/1449808460_952004.png) 调试的是有值的![图片说明](https://img-ask.csdn.net/upload/201512/11/1449823354_830574.png) 啊啊啊啊啊啊弄了好久啊,谁知道什么问题的帮帮我啊

MyBatis动态代理实现无接口实现类操作数据库实现原理

# MyBatis动态代理 我们知道MyBatis通过动态代理的方式,实现了只通过Mapper接口而无接口的实现类的方式操作数据库。 熟悉源码的同学应该知道如下代码(MapperProxy.invoke()): ``` @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { //如果目标方法继承自Object,则直接调用目标方法 if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else if (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } //从缓存中取出MapperMethod对象,如果缓存中没有,则创建新的MapperMethod对象并添加到缓存中 final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); } ``` 这种方式类似于截获了真正的代理对象,而去执行其他的逻辑,通过MapperMethod实现数据库的访问操作! # 代理对象的获取 MyBatis中的代理对象的获取是通过如下代码实现的: ``` public T newInstance(SqlSession sqlSession) { //创建MapperProxy对象,每次调用都会创建新的MapperProxy对象 final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); } /** * 创建实现了mapperInterface接口的代理对象 * @param mapperProxy * @return */ @SuppressWarnings("unchecked") protected T newInstance(MapperProxy<T> mapperProxy) { T t = (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); } ``` 返回的记过是这样的: ![图片说明](https://img-ask.csdn.net/upload/201711/09/1510219006_365523.png) 也就是说,无论调用的是哪一个Mapper接口,返回的代理对象都是MapperProxy类型的。 # 自己实现MyBatis动态代理模拟上述过程 ![图片说明](https://img-ask.csdn.net/upload/201711/09/1510219069_461051.png) ``` public class MapperRegistry { private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>(); public <T> T getMapper(Class<T> type) { //模拟初始化knownMappers集合 knownMappers.put(type, new MapperProxyFactory<T>(type)); final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); return (T) mapperProxyFactory.newInstance(); } } ``` ``` public class MapperProxyFactory<T> { private final Class<T> mapperInterface; public MapperProxyFactory(Class<T> mapperInterface) { this.mapperInterface = mapperInterface; } public T newInstance() { final MapperProxy<T> mapperProxy = new MapperProxy<>(mapperInterface); return newInstance(mapperProxy); } protected T newInstance(MapperProxy<T> mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); } } ``` ``` public class MapperProxy<T> implements InvocationHandler, Serializable { private static final long serialVersionUID = -6424540398559729838L; //真正的业务对象,也就是RealSubject对象 private Class<T> mapperInterface; /** * 构造函数 */ public MapperProxy(Class<T> target) { this.mapperInterface = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final MapperMethod mapperMethod = new MapperMethod(); return mapperMethod.execute(args); } } ``` ``` public class MapperMethod { public Object execute(Object[] args) { return new User("123", "234"); } } ``` ``` public class DefaultSqlSession { private Configuration configuration = new Configuration(); public <T> T getMapper(Class<T> type) { return configuration.getMapper(type); } } ``` ``` public class Configuration { final MapperRegistry mapperRegistry = new MapperRegistry(); public <T> T getMapper(Class<T> type) { return mapperRegistry.getMapper(type); } } ``` ``` public class UserService { public static void main(String[] args) { final DefaultSqlSession sqlSession = new DefaultSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUser(); System.out.println(user.toString()); } } ``` ``` public interface UserMapper { User selectUser(); } ``` 自己写的代码中抽取了MyBatis下binding包的主要内容实现的一个简单的动态获取实例,但是获取代理对象的时候,返回的记过是这样的: ![图片说明](https://img-ask.csdn.net/upload/201711/09/1510219292_564405.png) 可以看出,上述的过程的代理返回的类型并不是MapperProxy,虽然可以获取到正确的执行结果,但是返回的代理的对象类型是出现了转换异常的。 # 问题描述 1、为什么sqlSession.getMapper()返回的代理对象结果都是MapperProxy类型的,设计的初衷? 2、为什么我按照上述相同的代码过程自己实现的动态代理,为什么会出现转换异常? 还请各位大哥哥大姐姐帮忙研究一下,谢谢!

安卓listview item单击事件跳转空指针问题

两个activity源码, mainactivity: package com.example.newsclient; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.example.gxfi.entity.News; import com.example.gxfi.service.GetXmlAndParse; import android.R.string; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { private List listNews; private ListView list; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub switch (msg.what) { case GetXmlAndParse.PARSESUCCWSS: listNews = (List) msg.obj; initData(); break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = (ListView) findViewById(R.id.list); GetXmlAndParse getXmlAndParse = new GetXmlAndParse(mHandler); getXmlAndParse.getXml(); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub switch (parent.getId()) { case R.id.list: expressItemClick(position);//position 代表你点的哪一个 break; } } private void expressItemClick(int position) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this,NewsActivity.class); Map<String, String> item = (Map<String, String>) list.getAdapter().getItem(position); String essay = item.get("description"); //添加到intent域中 intent.putExtra("description",essay ); startActivity(intent); finish(); }}); } /** * 将解析后的xml填充到ListView */ protected void initData() { // TODO Auto-generated method stub List items = new ArrayList(); for (News news : (List<News>)listNews) { Map item = new HashMap(); item.put("title", news.getTitle()); item.put("description", news.getDescription()); items.add(item); } SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.news_view, new String[] { "title" }, new int[] { R.id.textView1 }); list.setAdapter(adapter); } } newsactivity: package com.example.newsclient; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class NewsActivity extends Activity { private TextView myTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = getIntent(); String value = intent.getStringExtra("description"); myTextView = (TextView) findViewById(R.id.textview2); // myTextView.setText(value); } } 错误: ![图片说明](https://img-ask.csdn.net/upload/201606/19/1466349934_182376.png)

kafka消费者迭代器卡死

配置kafka+zk在虚拟机上,自己在本机上的生产者可以正常发送消息,但是消费者在 ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); 之后 iterator 的任何操作都直接卡死了,请问这个是怎么回事?在这个操作之前debug是可以看到变量内部的数值的,这个操作之后就不能看了,value全部清空了。 贴源码 ``` package com.weixinjia.recreation.queue.client; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import kafka.consumer.ConsumerConfig; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; import kafka.message.MessageAndMetadata; public class ConsumerGroupExample extends Thread{ private final ConsumerConnector consumer; private final String topic; private ExecutorService executor; public ConsumerGroupExample(String a_zookeeper, String a_groupId, String a_topic) { consumer = kafka.consumer.Consumer.createJavaConsumerConnector( createConsumerConfig(a_zookeeper, a_groupId)); this.topic = a_topic; } public void shutdown() { if (consumer != null) consumer.shutdown(); if (executor != null) executor.shutdown(); try { if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) { System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly"); } } catch (InterruptedException e) { System.out.println("Interrupted during shutdown, exiting uncleanly"); } } public void run(int a_numThreads) { Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(topic, new Integer(a_numThreads)); Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap); List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic); // now launch all the threads // // executor = Executors.newFixedThreadPool(a_numThreads); System.out.println(streams.size()); // now create an object to consume the messages // int threadNumber = 0; for (final KafkaStream<byte[], byte[]> stream : streams) { executor.submit(new ConsumerTest(stream, threadNumber)); threadNumber++; ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); System.out.println(iterator); while(iterator.hasNext()){ MessageAndMetadata<byte[], byte[]> next = iterator.next(); byte[] message = next.message(); String string = new String(message); System.out.println(string); } } System.out.println("消息输出完成"); } private static ConsumerConfig createConsumerConfig(String a_zookeeper, String a_groupId) { Properties props = new Properties(); props.put("zookeeper.connect", a_zookeeper); props.put("group.id", a_groupId); props.put("zookeeper.session.timeout.ms", "1500"); props.put("zookeeper.sync.time.ms", "4000"); props.put("auto.commit.interval.ms", "1000"); props.put("fetch.message.max.bytes", "10240000"); props.put("auto.commit.enable", "true"); return new ConsumerConfig(props); } public static void main(String[] args) { String zooKeeper = "masterServce:2181"; String groupId = "group-1"; String topic = "test2"; int threads = 3; ConsumerGroupExample example = new ConsumerGroupExample(zooKeeper, groupId, topic); example.run(threads); try { Thread.sleep(10000); } catch (InterruptedException ie) { } example.shutdown(); } } ``` 消息在kafka那边直接用kafka-console-consumer.sh是可以查询到的

android studio做了个APP,其它用了JSOUP,碰到dopostback函数,无法加载

HfztbAcitivity package linpeng.ztb; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.opengl.Visibility; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.HorizontalScrollView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class HfztbActivity extends Activity implements OnClickListener { private GridView xml_gridview; private ListView xml_newslist; private Button foot_loadmore, prepare_refresh, gotoright, up, down, gotoother, gotoother2, gotoother3, gotoother4, gotoother5; private TextView foot_text; private ProgressBar foot_progressbar; private HorizontalScrollView horizontalScrollView; private SimpleAdapter listview_adapter; private ProgressBar refresh; private String list_button = "title1"; private int changenewslist = 1; private int[][] location = new int[5][2]; private boolean fist_open_title1 = true, fist_open_title2 = true, fist_open_title3 = true, fist_open_title4 = true, fist_open_title5 = true, goto_other_visiably = false;//fist_open_title6 = true, //fist_open_title7 = true, private boolean is_first_open = true; private final int FLINGDIS = 900; private List<Map<String, Object>> newslist = new ArrayList<Map<String, Object>>(); private List<Map<String, Object>> tempnewslist = new ArrayList<Map<String, Object>>(); private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.arg1 > -1) { prepare_refresh.setVisibility(0); refresh.setVisibility(8); Log.i("list_button", new IntToStrong().getname(msg.arg1) + list_button); changeFirstOpen(msg.arg1); if (list_button.equals(new IntToStrong().getname(msg.arg1))) { getNewsList(msg.arg1, false); } } if (msg.arg1 == -1) { prepare_refresh.setVisibility(0); refresh.setVisibility(8); Toast.makeText(HfztbActivity.this, "网络不通,请稍候再试", Toast.LENGTH_SHORT).show(); } } private void changeFirstOpen(int arg1) { if (arg1 == 0 && fist_open_title1) { fist_open_title1 = false; } else if (arg1 == 1 && fist_open_title2) { fist_open_title2 = false; } else if (arg1 == 2 && fist_open_title3) { fist_open_title3 = false; } else if (arg1 == 3 && fist_open_title4) { fist_open_title4 = false; } else if (arg1 == 4 && fist_open_title5) { fist_open_title5 = false; // } else if (arg1 == 5 && fist_open_title6) { // fist_open_title6 = false; // } else if (arg1 == 6 && fist_open_title7) { // fist_open_title7 = false; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); xml_gridview = (GridView) findViewById(R.id.xml_gridview); xml_gridview.setSelector(new ColorDrawable(Color.TRANSPARENT)); xml_newslist = (ListView) findViewById(R.id.newslist); prepare_refresh = (Button) findViewById(R.id.prepare_refresh); refresh = (ProgressBar) findViewById(R.id.refresh); gotoright = (Button) findViewById(R.id.gotoright); horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView); up = (Button) findViewById(R.id.up); down = (Button) findViewById(R.id.down); gotoother = (Button) findViewById(R.id.gotoother); gotoother2 = (Button) findViewById(R.id.gotoother2); gotoother3 = (Button) findViewById(R.id.gotoother3); gotoother4 = (Button) findViewById(R.id.gotoother4); gotoother5 = (Button) findViewById(R.id.gotoother5); LayoutInflater layoutInflater = getLayoutInflater(); View footView = layoutInflater.inflate(R.layout.foot, null); xml_newslist.addFooterView(footView); foot_loadmore = (Button) findViewById(R.id.foot_loadmore); foot_text = (TextView) findViewById(R.id.foot_text); foot_progressbar = (ProgressBar) findViewById(R.id.foot_progressbar); foot_loadmore.setOnClickListener(this); prepare_refresh.setOnClickListener(this); gotoright.setOnClickListener(this); up.setOnClickListener(this); down.setOnClickListener(this); gotoother.setOnClickListener(this); gotoother2.setOnClickListener(this); gotoother3.setOnClickListener(this); gotoother4.setOnClickListener(this); gotoother5.setOnClickListener(this); getNewsList(0, false); SimpleAdapter gridview_adapter = new SimpleAdapter(this, new ListData().getGridviewdata(), R.layout.gridview, new String[] { "grid_title" }, new int[] { R.id.grid_title }); listview_adapter = new SimpleAdapter(this, newslist, R.layout.newslistdetails, new String[] { "news_isend", "news_title", "news_time" }, new int[] { R.id.news_isend, R.id.news_title, R.id.news_time }); is_first_open = false; xml_gridview.setAdapter(gridview_adapter); xml_gridview.setOnItemClickListener(new onGridViewItemClick()); xml_newslist.setOnItemClickListener(new onListViewItemClick()); xml_newslist.setAdapter(listview_adapter); } private void getloction() { gotoother.getLocationOnScreen(location[0]); gotoother2.getLocationOnScreen(location[1]); gotoother3.getLocationOnScreen(location[2]); gotoother4.getLocationOnScreen(location[3]); gotoother5.getLocationOnScreen(location[4]); Log.i("x", location[0][0] + " " + location[0][1]); } private void getNewsList(int table_number, boolean is_fresh) { boolean has_fresh = false; String table_name = new IntToStrong().getname(table_number); DataBaseHelper dbh = new DataBaseHelper(this, table_name, null, 1); SQLiteDatabase sql = dbh.getReadableDatabase(); Cursor cursor = sql.query(table_name, new String[] { "newsclass", "newstitle", "newstime", "isread" }, "newsclass>?", new String[] { "-1" }, null, null, null); if (cursor.getCount() != 0 && is_fresh == false) { newslist.clear(); getNewsListByDatabase(cursor); prepare_refresh.setVisibility(0); refresh.setVisibility(8); if (!is_first_open) { listview_adapter.notifyDataSetChanged(); xml_newslist.setSelection(0); list_button = new IntToStrong().getname(table_number); } } else { list_button = new IntToStrong().getname(table_number); MyThread myThread = new MyThread(table_number, HfztbActivity.this); has_fresh = true; myThread.start(); } if (!has_fresh) { reFresh(table_name, table_number); } if (sql != null) { sql.close(); } if (dbh != null) { dbh.close(); } } private void reFresh(String table_name, int table_number) { if (fist_open_title1 && table_name == "title1") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title2 && table_name == "title2") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title3 && table_name == "title3") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title4 && table_name == "title4") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title5 && table_name == "title5") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); //} else if (fist_open_title6 && table_name == "title6") { // MyThread myThread = new MyThread(table_number, HfztbActivity.this); // myThread.start(); //} else if (fist_open_title7 && table_name == "title7") { // MyThread myThread = new MyThread(table_number, HfztbActivity.this); // myThread.start(); } } private void getNewsListByDatabase(Cursor cursor) { newslist.clear(); while (cursor.moveToNext()) { Map<String, Object> map = new HashMap<String, Object>(); map.put("news_title", cursor.getString(cursor.getColumnIndex("newstitle"))); map.put("news_time", cursor.getString(cursor.getColumnIndex("newstime"))); map.put("news_isend", cursor.getString(cursor.getColumnIndex("isread"))); newslist.add(map); } } class onGridViewItemClick implements OnItemClickListener { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { int table_number = arg2; TextView gridviewback = (TextView) arg1; for (int i = 0; i < arg0.getCount(); i++) { TextView gridview_text_temp = (TextView) arg0.getChildAt(i); gridview_text_temp.setBackgroundDrawable(null); gridview_text_temp.setTextColor(getResources().getColor( R.color.grid_title_color)); } gridviewback.setBackgroundResource(R.drawable.gridviewbackground); gridviewback.setTextColor(Color.WHITE); if (arg2 >= 0 && arg2 <= 6) { getNewsList(table_number, false); Log.i("after", "thread"); } } } class onListViewItemClick implements OnItemClickListener { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { DataBaseHelper dbh = new DataBaseHelper(HfztbActivity.this, list_button, null, 1); SQLiteDatabase sq = dbh.getReadableDatabase(); Cursor cursor = sq.query(list_button, new String[] { "newsclass", "newstitle", "newstime", "isread", "url" }, "newsclass=?", new String[] { arg2 + "" }, null, null, null); cursor.moveToNext(); Intent intent = new Intent(HfztbActivity.this, News.class);// ��ת������ҳ if (!cursor.isAfterLast()) { intent.putExtra("newsurl", cursor.getString(cursor.getColumnIndex("url"))); intent.putExtra("newstitle", cursor.getString(cursor.getColumnIndex("newstitle"))); intent.putExtra("newstime", cursor.getString(cursor.getColumnIndex("newstime"))); intent.putExtra("type", list_button); startActivity(intent); } if (dbh != null) { dbh.close(); sq.close(); } } } public class MyThread extends Thread { private int table_number; private Context context; public MyThread(int table_number, Context context) { this.table_number = table_number; this.context = context; } @Override public void run() { getNewsList(table_number); } protected void getNewsList(int table_number) { try { Document doc; String url = "http://ggzy.jiangxi.gov.cn/jxzbw/jyxx/002004/00200400" + (table_number + 1) + "/MoreInfo.aspx?CategoryNum=00200400"+ (table_number + 1); doc = Jsoup.connect(url).get(); new ListData().getListData(doc, table_number, context, url); Message msg = handler.obtainMessage(); msg.arg1 = table_number; handler.sendMessage(msg); } catch (IOException e) { Log.i("tag", "error"); Message msg = handler.obtainMessage(); msg.arg1 = -1; handler.sendMessage(msg); e.printStackTrace(); } } } public void onClick(View v) { if (v.getId() == foot_loadmore.getId()) { foot_loadmore.setVisibility(8); foot_text.setVisibility(0); foot_progressbar.setVisibility(0); } if (v.getId() == prepare_refresh.getId()) { prepare_refresh.setVisibility(8); refresh.setVisibility(0); getNewsList(new IntToStrong().table_name_to_int(list_button), true); } if (v.getId() == gotoright.getId()) { horizontalScrollView.fling(FLINGDIS); Log.i("" + horizontalScrollView.getScrollY(), horizontalScrollView.getScrollX() + ""); } if (v.getId() == up.getId()) { xml_newslist.setSelection(0); } if (v.getId() == down.getId()) { Log.i("asff", xml_newslist.getScrollY() + ""); xml_newslist.setSelection(1000); } if (v.getId() == gotoother.getId()) { getloction(); if (!goto_other_visiably) { setVisiablyAndAnimation(false, -1); } else { Log.i("x", location[0][0] + " " + location[0][1]); setVisiablyAndAnimation(true, 0); } } if (v.getId() == gotoother2.getId()) { setVisiablyAndAnimation(false, 0); } if (v.getId() == gotoother3.getId()) { setVisiablyAndAnimation(false, 1); } if (v.getId() == gotoother4.getId()) { setVisiablyAndAnimation(false, 2); } if (v.getId() == gotoother5.getId()) { setVisiablyAndAnimation(false, 3); } } private void setVisiablyAndAnimation(boolean b, int which) { if (!b && which > -1) { ScaleAnimation[] scaleAnimations = getScaleAnimation(which); gotoother2.startAnimation(scaleAnimations[0]); gotoother3.startAnimation(scaleAnimations[1]); gotoother4.startAnimation(scaleAnimations[2]); gotoother5.startAnimation(scaleAnimations[3]); gotoother2.setVisibility(8); gotoother3.setVisibility(8); gotoother4.setVisibility(8); gotoother5.setVisibility(8); goto_other_visiably = false; } else if (which == -1) { TranslateAnimation[] translateAnimations = getTranslateAnimation(which); gotoother2.startAnimation(translateAnimations[0]); gotoother3.startAnimation(translateAnimations[1]); gotoother4.startAnimation(translateAnimations[2]); gotoother5.startAnimation(translateAnimations[3]); gotoother2.setVisibility(0); gotoother3.setVisibility(0); gotoother4.setVisibility(0); gotoother5.setVisibility(0); goto_other_visiably = true; } else { TranslateAnimation[] translateAnimations = getTranslateAnimation(which); gotoother2.startAnimation(translateAnimations[0]); gotoother3.startAnimation(translateAnimations[1]); gotoother4.startAnimation(translateAnimations[2]); gotoother5.startAnimation(translateAnimations[3]); gotoother2.setVisibility(8); gotoother3.setVisibility(8); gotoother4.setVisibility(8); gotoother5.setVisibility(8); goto_other_visiably = false; } } private TranslateAnimation[] getTranslateAnimation(int which) { TranslateAnimation[] translateAnimations = new TranslateAnimation[4]; if (which == -1) { translateAnimations[0] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[1][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[1][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[1] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[2][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[2][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[2] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[3][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[3][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[3] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[4][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[4][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[0].setDuration(100); translateAnimations[1].setDuration(150); translateAnimations[2].setDuration(200); translateAnimations[3].setDuration(250); } else { translateAnimations[0] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[1][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[1][1]); translateAnimations[1] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[2][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[2][1]); translateAnimations[2] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[3][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[3][1]); translateAnimations[3] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[4][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[4][1]); translateAnimations[0].setDuration(250); translateAnimations[1].setDuration(200); translateAnimations[2].setDuration(150); translateAnimations[3].setDuration(100); } return translateAnimations; } private ScaleAnimation[] getScaleAnimation(int which) { ScaleAnimation[] scaleAnimations = new ScaleAnimation[4]; scaleAnimations[0] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[1] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[2] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[3] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[which] = new ScaleAnimation(1, 1.7f, 1, 1.7f); scaleAnimations[0].setDuration(150); scaleAnimations[1].setDuration(150); scaleAnimations[2].setDuration(150); scaleAnimations[3].setDuration(150); return scaleAnimations; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Builder builder = new Builder(this); builder.setMessage("确定退出吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { System.exit(0); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.show(); } return true; } } Listdata package linpeng.ztb; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class ListData { public List<Map<String, String>> getGridviewdata() { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); HashMap<String, String> hash = new HashMap<String, String>(); hash.put("grid_title", "采购公告"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "变更公告"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "答疑澄清"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "结果公示"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "单一来源"); list.add(hash); //hash = new HashMap<String, String>(); //hash.put("grid_title", "标前公示ʾ"); //list.add(hash); //hash = new HashMap<String, String>(); //hash.put("grid_title", "巢湖"); //list.add(hash); return list; } public void getListData(Document doc, int table_number, Context context, String url) { try { Element ele = doc.select("td[height=500]").first(); Elements eles = ele.select("a"); int newsclass = 0; String table_name = new IntToStrong().getname(table_number); if (ele.text().length() > 1) { DataBaseHelper dbh = new DataBaseHelper(context, table_name, null, 1); Log.i("shanchu", "ca"); dbh.dellAll(); } if (table_number != 3 && table_number != 5) { for (Element ele2 : eles) { String inittext = ele2.text(); String isend = "报名结束"; String changetext = inittext.replace("【正在报名】", "");// 替换文中的【正在报名】 String newsurl = ele2.attr("abs:href"); if (changetext.length() != inittext.length()) { isend = "正在报名"; } else { changetext = changetext.replace("【报名结束】", "");// 替换文中的【报名结束】 } if (ele2.text().replace("更多信息", "").length() >= 2) { DataBaseHelper dbh = new DataBaseHelper(context, table_name, null, 1); SQLiteDatabase sqh = dbh.getWritableDatabase(); dbh.addnewslist(newsclass, changetext, ele2.parent() .parent().select("td").last().text(), isend, newsurl); newsclass++; } } } else { for (Element ele2 : eles) { String inittext = ele2.text(); String newsurl = ele2.attr("abs:href"); String name = new IntToStrong().getname(table_number); if (ele2.text().replace("更多信息", "").length() >= 2) { DataBaseHelper dbh = new DataBaseHelper(context, name, null, 1); SQLiteDatabase sqh = dbh.getWritableDatabase(); dbh.addnewslist(newsclass, inittext, ele2.parent() .parent().select("td").last().text(), "", newsurl); newsclass++; } } } } catch (Exception e) { Log.i("s", "网络不通"); // Toast.makeText(context, "网络不通,请稍候再试",Toast.LENGTH_SHORT).show(); } } } NEWS package linpeng.ztb; import java.util.HashMap; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.R.integer; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RemoteViews.ActionException; import android.widget.TextView; import android.widget.Toast; public class News extends Activity { private TextView news_details_text, news_details_title, news_details_time; private ProgressBar news_details_progress; private int flag = 1, arg2, text_size;// flag=1表示从网络获取数据=0表示从数据库获取数据 private String kind, url; private String newsdetailstext = "", downloadtext = "", downloadaddress = "", type; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.arg1) { case 1: if (newsdetailstext.length() > 3) { putData(); } else { Toast.makeText(News.this, "网络不通,请稍后再试", Toast.LENGTH_SHORT) .show(); } news_details_text.setText(newsdetailstext); news_details_progress.setVisibility(8); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.news); Intent intent = getIntent(); SharedPreferences s = getSharedPreferences("text_size", 0); text_size = s.getInt("text_size", 20); url = intent.getStringExtra("newsurl"); type = intent.getStringExtra("type"); String newstitle = intent.getStringExtra("newstitle"); String newstime = intent.getStringExtra("newstime"); news_details_text = (TextView) findViewById(R.id.news_details_text); news_details_title = (TextView) findViewById(R.id.news_details_title); news_details_time = (TextView) findViewById(R.id.news_details_time); news_details_progress = (ProgressBar) findViewById(R.id.news_details_progress); news_details_progress.setVisibility(0); news_details_title.setText(newstitle); news_details_time.setText(newstime); news_details_text.setTextSize(text_size); flag = 0; DataBaseHelper dbh = new DataBaseHelper(this, new IntToStrong().TypeToType(type), null, 1); SQLiteDatabase sql = dbh.getReadableDatabase(); Cursor cursor = sql.query(new IntToStrong().TypeToType(type), new String[] { "newsurl", "newstitle", "newstime", "newsdetails", "newsdownloadtext1", "newsdownloadurl1", "newsdownloadtext2", "newsdownloadurl2" }, "newsurl=?", new String[] { url }, null, null, null); cursor.moveToNext(); if (cursor.getCount() == 0) { new NewsThread().start(); } else { news_details_text.setText(cursor.getString(cursor .getColumnIndex("newsdetails"))); news_details_progress.setVisibility(8); } if (sql != null) { sql.close(); } } protected void putData() { DataBaseHelper dbh = new DataBaseHelper(this, new IntToStrong().TypeToType(type), null, 1); SQLiteDatabase sql = dbh.getWritableDatabase(); dbh.addetails(url, news_details_title.getText().toString(), news_details_time.getText().toString(), newsdetailstext, null, null, null, null); if (dbh != null) { dbh.close(); sql.close(); } } private void getNews() { try { String host = android.net.Proxy.getDefaultHost(); int port = android.net.Proxy.getDefaultPort(); Document doc = Jsoup.connect(url).get(); Element ele = doc.getElementById("TDContent"); int j = 1; if (ele.children().text().length() < 2) { System.out.println(1); newsdetailstext = newsdetailstext + ele.text(); } for (Element ele2 : ele.children()) { j++; newsdetailstext = newsdetailstext + ele2.text(); newsdetailstext = newsdetailstext + "\n"; newsdetailstext = newsdetailstext + "\n"; } if (j == 2) { newsdetailstext = ""; for (Element ele2 : ele.children()) { for (Element ele3 : ele2.children()) { System.out.println(3); newsdetailstext = newsdetailstext + ele3.text(); newsdetailstext = newsdetailstext + "\n"; newsdetailstext = newsdetailstext + "\n"; } } } } catch (Exception e) { e.printStackTrace(); } } private class NewsThread extends Thread { @Override public void run() { getNews(); Message msg = handler.obtainMessage(); msg.arg1 = 1; handler.sendMessage(msg); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(menu.NONE, 1, 1, "字体大小"); menu.add(menu.NONE, 2, 1, "使用浏览器打开此页面"); menu.add(menu.NONE, 3, 1, "拨打此页面中电话"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: Builder builder = new Builder(this); builder.setTitle("字体大小"); builder.setSingleChoiceItems(new String[] { "大", "中", "小" }, new IntToStrong().text_size_to_order(text_size), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { news_details_text.setTextSize(24); SharedPreferences sp = getSharedPreferences( "text_size", 0); sp.edit().putInt("text_size", 24).commit(); dialog.cancel(); } else if (which == 1) { news_details_text.setTextSize(20); SharedPreferences sp = getSharedPreferences( "text_size", 0); sp.edit().putInt("text_size", 20).commit(); dialog.cancel(); } else if (which == 2) { news_details_text.setTextSize(16); SharedPreferences sp = getSharedPreferences( "text_size", 0); sp.edit().putInt("text_size", 16).commit(); dialog.cancel(); } } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.show(); break; case 2: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); break; case 3: Builder builder2=new Builder(this); Map telephone=getTelePhone(); //LayoutInflater inflater=getLayoutInflater(); //View layout=inflater.inflate(R.layout.telephone,(ViewGroup)findViewById(R.id.news_tele)); Intent intent1 = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ telephone.get("tele"+1))); startActivity(intent1); //builder2.setView(layout); //builder2.show(); break; default: break; } return true; } private Map getTelePhone() { Map telephone = new HashMap<String, String>(); if (news_details_text.length() > 5) { int temp_index_telephone=1; String text = news_details_text.getText().toString(); for (int i = 1; i <= text.length() - 1; i++) { if (text.charAt(i) == '电' && text.charAt(i + 1) == '话' || text.charAt(i) == '电' && text.charAt(i + 2) == '话') { int k = 3; if(text.charAt(i+2)=='话'){ k=4; } String temp_telephone=""; while (text.charAt(i + k) == '1' || text.charAt(i + k) == '2' || text.charAt(i + k) == '3' || text.charAt(i + k) == '4' || text.charAt(i + k) == '5' || text.charAt(i + k) == '6' || text.charAt(i + k) == '7' || text.charAt(i + k) == '8' || text.charAt(i + k) == '9' || text.charAt(i + k) == '-' || text.charAt(i + k) == '0') { temp_telephone=temp_telephone+text.charAt(i+k); k++; } if(temp_telephone.length()>5){ temp_telephone=temp_telephone.replace("-",""); telephone.put("tele"+temp_index_telephone, temp_telephone); Log.i("sasaa", "" + temp_telephone); temp_index_telephone++; temp_telephone=""; } } } } return telephone; } }

xfire 客户端调用出错,求高人指点

根据wsdl用myeclipse 生成的客户端,这个类为什么报错,后面的这些代码什么意思,求高人指点 props.put("annotations.allow.interface", true); AnnotationServiceFactory asf = new AnnotationServiceFactory( new Jsr181WebAnnotations(), tm, new AegisBindingProvider( new JaxbTypeRegistry())); asf.setBindingCreationEnabled(false); service0 = asf.create((com.zlkj.drvschool.webservice.jjzdvpnservicePortType.class),props); { AbstractSoapBinding soapBinding = asf.createSoap11Binding(service0, new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnserviceHttpBinding"), "http://schemas.xmlsoap.org/soap/http"); } { AbstractSoapBinding soapBinding = asf.createSoap11Binding(service0, new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnservicePortTypeLocalBinding"), "urn:xfire:transport:local"); } 下面是整个类源码 import java.net.MalformedURLException; import java.net.URLEncoder; import java.util.Collection; import java.util.HashMap; import javax.xml.namespace.QName; import org.codehaus.xfire.XFireRuntimeException; import org.codehaus.xfire.aegis.AegisBindingProvider; import org.codehaus.xfire.annotations.AnnotationServiceFactory; import org.codehaus.xfire.annotations.jsr181.Jsr181WebAnnotations; import org.codehaus.xfire.client.XFireProxyFactory; import org.codehaus.xfire.jaxb2.JaxbTypeRegistry; import org.codehaus.xfire.service.Endpoint; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.codehaus.xfire.soap.AbstractSoapBinding; import org.codehaus.xfire.transport.TransportManager; public class jjzdvpnserviceClient { private static XFireProxyFactory proxyFactory = new XFireProxyFactory(); private HashMap endpoints = new HashMap(); private Service service0; @SuppressWarnings("unchecked") public jjzdvpnserviceClient() { create0(); Endpoint jjzdvpnservicePortTypeLocalEndpointEP = service0.addEndpoint( new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnservicePortTypeLocalEndpoint"), new QName( "http://vpnservice.webservice.zlkj.com", "jjzdvpnservicePortTypeLocalBinding"), "xfire.local://jjzdvpnservice"); endpoints.put(new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnservicePortTypeLocalEndpoint"), jjzdvpnservicePortTypeLocalEndpointEP); Endpoint jjzdvpnserviceHttpPortEP = service0.addEndpoint(new QName( "http://vpnservice.webservice.zlkj.com", "jjzdvpnserviceHttpPort"), new QName( "http://vpnservice.webservice.zlkj.com", "jjzdvpnserviceHttpBinding"), "http://127.0.0.1:9080/traplugin/services/jjzdvpnservice"); endpoints.put(new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnserviceHttpPort"), jjzdvpnserviceHttpPortEP); } public Object getEndpoint(Endpoint endpoint) { try { return proxyFactory.create((endpoint).getBinding(), (endpoint).getUrl()); } catch (MalformedURLException e) { throw new XFireRuntimeException("Invalid URL", e); } } public Object getEndpoint(QName name) { Endpoint endpoint = ((Endpoint) endpoints.get((name))); if ((endpoint) == null) { throw new IllegalStateException("No such endpoint!"); } return getEndpoint((endpoint)); } public Collection getEndpoints() { return endpoints.values(); } @SuppressWarnings("unchecked") private void create0() { TransportManager tm = (org.codehaus.xfire.XFireFactory.newInstance() .getXFire().getTransportManager()); HashMap props = new HashMap(); props.put("annotations.allow.interface", true); AnnotationServiceFactory asf = new AnnotationServiceFactory( new Jsr181WebAnnotations(), tm, new AegisBindingProvider( new JaxbTypeRegistry())); asf.setBindingCreationEnabled(false); service0 = asf.create((com.zlkj.drvschool.webservice.jjzdvpnservicePortType.class),props); { AbstractSoapBinding soapBinding = asf.createSoap11Binding(service0, new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnserviceHttpBinding"), "http://schemas.xmlsoap.org/soap/http"); } { AbstractSoapBinding soapBinding = asf.createSoap11Binding(service0, new QName("http://vpnservice.webservice.zlkj.com", "jjzdvpnservicePortTypeLocalBinding"), "urn:xfire:transport:local"); } } public jjzdvpnservicePortType getjjzdvpnservicePortTypeLocalEndpoint() { return ((jjzdvpnservicePortType) (this).getEndpoint(new QName( "http://vpnservice.webservice.zlkj.com", "jjzdvpnservicePortTypeLocalEndpoint"))); } public jjzdvpnservicePortType getjjzdvpnservicePortTypeLocalEndpoint( String url) { jjzdvpnservicePortType var = getjjzdvpnservicePortTypeLocalEndpoint(); org.codehaus.xfire.client.Client.getInstance(var).setUrl(url); return var; } public jjzdvpnservicePortType getjjzdvpnserviceHttpPort() { return ((jjzdvpnservicePortType) (this).getEndpoint(new QName( "http://vpnservice.webservice.zlkj.com", "jjzdvpnserviceHttpPort"))); } public jjzdvpnservicePortType getjjzdvpnserviceHttpPort(String url) { jjzdvpnservicePortType var = getjjzdvpnserviceHttpPort(); org.codehaus.xfire.client.Client.getInstance(var).setUrl(url); return var; } }

前端jsencrypt加密,后端无法解密

## 前后端RSA加密 > 在做一个web安全登录的作业时,遇到前后端RSA加密问题。。 1. 后端 java 生成RSA密钥对,privateKey,publicKey 后端RSA是从帖子上抄的: (学习加密四spring boot 使用RSA+AES混合加密,前后端传递参数加解密)[https://blog.csdn.net/baidu_38990811/article/details/83540404] **使用PKCS8规范** ``` // 后端部分代码 RSA /** * 生成密钥对(公钥和私钥) * @return * @throws Exception */ public static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(INITIALIZE_LENGTH); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** * 私钥解密 * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } ``` 2. 前端:vue+webpack - 从后端获取一个公钥**publicKey** - 使用jsencrypt 和 **publicKey**加密内容,得到String encrypted 3. 后端拿到传回的encrypted, 再解密时报错 ``` javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:383) at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:294) at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363) at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) at javax.crypto.Cipher.doFinal(Cipher.java:2222) at com.security.loginserver.Util.RSAUtils.decryptByPrivateKey(RSAUtils.java:126) at com.security.loginserver.Util.RSAUtils.decryptDataOnJava(RSAUtils.java:285) ``` ## 测试情况 1. 后端单独测试RSA加密解密,正常 2. 前端单独测试RSA加密解密,使用后端的publicKey和privatekey正常 3. 搜到的贴子说,原因是JSEncrypt使用pkcs1规范,后端java用了**PKCS8规范**,,,然后就无从下手了 4. 求助大佬

appium切换到webview后,获取不了真实的html页面,应该怎么处理?

**问题** 我使用appium 测试我公司的混合app,使用driver.context("WebView")切换到webview后,调用getPageSource(),返回如下 ``` <html xmlns="http://www.w3.org/1999/xhtml"><head></head><body><iframe name="chromedriver dummy frame" src="about:blank"></iframe></body></html> ``` **环境:** ``` appium:1.15.1 OS:Windows 10 API :java Android:8.1 ``` **chrome inspect** ![chrome inspect 图片](https://i.stack.imgur.com/X9L6U.png) ![图片说明](https://i.stack.imgur.com/V8Ldq.png) **配置代码** ``` capabilities.setCapability("platformName", "Android"); capabilities.setCapability("deviceName", "b307aa10"); capabilities.setCapability("automationName", "appium"); capabilities.setCapability("platformVersion", "8.1.0"); capabilities.setCapability("appPackage", "com.dayizhihui.dayishi.hpv"); capabilities.setCapability("appActivity", ".main.view.WelcomeActivity"); capabilities.setCapability("noReset", "true"); Map<String, Object> chromeOptions = new HashMap<String, Object>(); chromeOptions.put("androidPackage", "com.android.chrome"); capabilities.setCapability(ChromeOptions.CAPABILITY,chromeOptions); ``` **程序代码** ``` driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); introducePageHandle.clickIntroduceIcon(); System.out.println("Before " + driver.getContext()); System.out.println("All Contexts " + driver.getContextHandles()); driver.context("WEBVIEW_com.dayizhihui.dayishi.hpv"); System.out.println("After " + driver.getContext()); System.out.println("PageSource " + driver.getPageSource()); ``` **输出如下** ``` Before NATIVE_APP All Contexts [NATIVE_APP, WEBVIEW_com.dayizhihui.dayishi.hpv, WEBVIEW_chrome] After WEBVIEW_com.dayizhihui.dayishi.hpv PageSource <html xmlns="http://www.w3.org/1999/xhtml"><head></head><body><iframe name="chromedriver dummy frame" src="about:blank"></iframe></body></html> ```

Strust2 s标签下的doubleselect 第二级下拉框获取不到值

在form表单中 用S标签的doubleselect 写了一个二级联动的下拉选择框 一级的下拉框list拿到了 也能显示出来 但是二级的map页面可以获取到 在值栈里 但是二级下拉框怎么也不能获取map里的key和value 以下是源码 新手实在找不出问题所在 求大神解答! 这是form里的doubleselect[图片说明](https://img-ask.csdn.net/upload/201710/14/1507965860_779566.jpg) BookFatherPlaceVO.java ``` package com.javasm.homework01; public class BookFatherPlaceVO { private String fatherPlaceId; private String fatherPlaceName; public BookFatherPlaceVO(){} public BookFatherPlaceVO(String fatherPlaceId , String fatherPlaceName){ this.fatherPlaceId = fatherPlaceId; this.fatherPlaceName = fatherPlaceName; } public String getFatherPlaceId() { return fatherPlaceId; } public void setFatherPlaceId(String fatherPlaceId) { this.fatherPlaceId = fatherPlaceId; } public String getFatherPlaceName() { return fatherPlaceName; } public void setFatherPlaceName(String fatherPlaceName) { this.fatherPlaceName = fatherPlaceName; } } ``` BookSonPlaceVO ``` package com.javasm.homework01; public class BookSonPlaceVO { private String BookSonPlaceId; private String BookSonPlaceName; public BookSonPlaceVO(){} public BookSonPlaceVO(String BookSonPlaceId , String BookSonPlaceName){ this.BookSonPlaceId = BookSonPlaceId; this.BookSonPlaceName = BookSonPlaceName; } public String getBookSonPlaceId() { return BookSonPlaceId; } public void setBookSonPlaceId(String bookSonPlaceId) { BookSonPlaceId = bookSonPlaceId; } public String getBookSonPlaceName() { return BookSonPlaceName; } public void setBookSonPlaceName(String bookSonPlaceName) { BookSonPlaceName = bookSonPlaceName; } } ``` BookTypeVOService ``` package com.javasm.homework01; import java.util.List; import java.util.Map; public interface BookTypeVOService { List<BookTypeVO> selectBookTypeVo(); List<BookFatherPlaceVO> selectBookFatherPlaceVO(); Map<String,List<String>> selectBookSonPlaceVO(); } ``` BookTypeVOServiceImpl ```package com.javasm.homework01; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class BookTypeVOServiceImpl implements BookTypeVOService{ public List<BookTypeVO> selectBookTypeVo() { List<BookTypeVO> list = new ArrayList<>(); /*BookTypeVO typeVO = new BookTypeVO(); typeVO.setTypeid("1"); typeVO.setTypename("玄幻奇幻"); list.add(typeVO); BookTypeVO typeVO1 = new BookTypeVO(); typeVO1.setTypeid("2"); typeVO1.setTypename("武侠仙侠"); list.add(typeVO1); BookTypeVO typeVO2 = new BookTypeVO(); typeVO1.setTypeid("3"); typeVO1.setTypename("都市言情"); list.add(typeVO2); BookTypeVO typeVO4 = new BookTypeVO(); typeVO1.setTypeid("4"); typeVO1.setTypename("科幻灵异"); list.add(typeVO4);*/ list.add(new BookTypeVO("1","玄幻奇幻")); list.add(new BookTypeVO("2","武侠仙侠")); list.add(new BookTypeVO("3","都市言情")); list.add(new BookTypeVO("4","科幻灵异")); return list; } public List<BookFatherPlaceVO> selectBookFatherPlaceVO() { List<BookFatherPlaceVO> list = new ArrayList<>(); list.add(new BookFatherPlaceVO("1","北京市")); list.add(new BookFatherPlaceVO("2","河北省")); list.add(new BookFatherPlaceVO("3","黑龙江省")); list.add(new BookFatherPlaceVO("4","广东省")); list.add(new BookFatherPlaceVO("5","山东省")); return list; } public Map<String, List<String>> selectBookSonPlaceVO() { Map<String, List<String>> map = new HashMap(); map.put("1",new ArrayList<String>(){{ add("海淀区"); add("朝阳区"); add("通州区"); add("丰台区"); add("顺义区"); }}); map.put("2",new ArrayList<String>(){{ add("邢台"); add("唐山"); add("石家庄"); add("张家口"); add("秦皇岛"); }}); map.put("3",new ArrayList<String>(){{ add("哈尔滨"); add("大庆"); add("齐齐哈尔"); add("牡丹江"); add("佳木斯"); add("东京"); }}); map.put("4",new ArrayList<String>(){{ add("广州"); add("深圳"); add("珠海"); add("厦门"); add("东莞"); }}); map.put("5",new ArrayList<String>(){{ add("济南"); add("青岛"); add("威海"); add("烟台"); add("蓬莱"); }}); return map; } } ``` BookVO ``` package com.javasm.homework01; public class BookVO { private String name; private String author; private String pageNum; private String type; private String father; private String son; public BookVO(){} public BookVO(String name,String author,String pageNum,String type,String father,String son){ this.name = name; this.author = author; this.pageNum = pageNum; this.type = type; this.father = father; this.son = son; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPageNum() { return pageNum; } public void setPageNum(String pageNum) { this.pageNum = pageNum; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getFather() { return father; } public void setFather(String father) { this.father = father; } public String getSon() { return son; } public void setSon(String son) { this.son = son; } } ``` action ``` package com.javasm.homework01; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HomeWork01Action { BookTypeVOService typeService = new BookTypeVOServiceImpl(); private BookVO book; private BookTypeVO type; private BookFatherPlaceVO fatherVO; private BookSonPlaceVO sonVO; private List<BookTypeVO> typeList; private List<BookFatherPlaceVO> fatherList; private Map<String, List<String>> sonMap; public String execute(){ return "execute"; } public String add(){ typeList = typeService.selectBookTypeVo(); fatherList = typeService.selectBookFatherPlaceVO(); sonMap = typeService.selectBookSonPlaceVO(); return "add"; } public String doAdd(){ return "doAdd"; } public BookVO getBook() { return book; } public void setBook(BookVO book) { this.book = book; } public List<BookTypeVO> getTypeList() { return typeList; } public void setTypeList(List<BookTypeVO> typeList) { this.typeList = typeList; } public List<BookFatherPlaceVO> getFatherList() { return fatherList; } public void setFatherList(List<BookFatherPlaceVO> fatherList) { this.fatherList = fatherList; } public Map<String, List<String>> getSonMap() { return sonMap; } public void setSonMap(Map<String, List<String>> sonMap) { this.sonMap = sonMap; } public BookFatherPlaceVO getFatherVO() { return fatherVO; } public void setFatherVO(BookFatherPlaceVO fatherVO) { this.fatherVO = fatherVO; } public BookSonPlaceVO getSonVO() { return sonVO; } public void setSonVO(BookSonPlaceVO sonVO) { this.sonVO = sonVO; } } ``` add页面 ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'homework01_add.jsp' starting page</title> </head> <body> <h1>我也是添加页面</h1> ${sonMap} <s:form method="get" action="homework01/add!doAdd.action"> <label>名称: <s:textfield name="book.name" value=""></s:textfield></label> <p>输入书籍作者: <s:textfield name="book.author" value=""></s:textfield></p> <p>输入书籍页数: <s:textfield name="book.pageNum" value=""></s:textfield></p> <p><s:select name="type" list="typeList" listKey="typeid" listValue="typename"></s:select></p> <p><s:doubleselect list="fatherList" listKey="fatherPlaceId" listValue="fatherPlaceName" doubleList="sonMap.get(top.fatherPlaceId)" doublelistKey ="fatherPlaceId" doubleListValue="BookSonPlaceName" name="father" doubleName="son"> </s:doubleselect></p> <s:submit value="提交"></s:submit> <s:debug></s:debug> </s:form> </body> </html> ``` 这是JSP报错页面![图片说明](https://img-ask.csdn.net/upload/201710/14/1507966419_813331.jpg) 还有一种就是在doubleListKey里写fatherPlaceId 在开发者模式里报![图片说明](https://img-ask.csdn.net/upload/201710/14/1507966541_124611.jpg) 总之就是map已经在值栈中 但是就是获取不到二级菜单的值~~~ 求大神帮忙

JAVA POST登录异常问题?

网上找的HTTP登录代码,登录后返回能200,但是不用用户名密码也返回200,且用Cookie[] cookies = httpClient.getState().getCookies(); StringBuffer tmpcookies = new StringBuffer(); for (Cookie c : cookies) { tmpcookies.append(c.toString() + ";"); System.out.println("cookies = "+c.toString()); } 能取到Cookies,这个搞不懂 登录成功后跳到另一个网页,但是用System.out.println("ResponseBody:\n" + stringBuffer.toString());返回如下: ``` <html> <head><title></title> <SCRIPT LANGUAGE="JavaScript"> var currentWindow = window; if(currentWindow != null){ currentWindow.top.location = "/NMMP/jsp/login.jsp"; } </SCRIPT> </head> ``` 感觉跳转时少了东西,所以跳转后的网页不对,请各们大神帮分析下,或者给个思路,本人不是搞程序的,只是想做一个来应对自己的重复工作,完整代码如下:本人无C币,如果有兴趣帮我做可商量 ``` import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; /** * * @ClassName: HttpLogin * @Description: java通过httpclient获取cookie模拟登录 * @author zeze * @date 2015年11月10日 下午4:18:08 * */ public class HttpLogin { public static void main(String[] args) { // 登陆 Url String loginUrl = "http://10.154.13.82:7011/NMMP/jsp/login.jsp"; // 需登陆后访问的 Url String dataUrl = "http://10.154.13.82:7011/NMMP/wyMainAction!init.ilf"; //http://10.154.13.82:7011/NMMP//jsp/wyService/mytasklist.jsp HttpClient httpClient = new HttpClient(); // 模拟登陆,按实际服务器端要求选用 Post 或 Get 请求方式 PostMethod postMethod = new PostMethod(loginUrl); // 设置登陆时要求的信息,用户名和密码 NameValuePair[] data = { new NameValuePair("useraccount", ""), new NameValuePair("password", "Hn_yd45") }; postMethod.setRequestBody(data); try { // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); int statusCode=httpClient.executeMethod(postMethod); // 获得登陆后的 Cookie Cookie[] cookies = httpClient.getState().getCookies(); StringBuffer tmpcookies = new StringBuffer(); for (Cookie c : cookies) { tmpcookies.append(c.toString() + ";"); System.out.println("cookies = "+c.toString()); } System.out.println(statusCode); if(statusCode==200){//重定向到新的URL System.out.println("模拟登录成功"); // 进行登陆后的操作 GetMethod getMethod = new GetMethod(dataUrl); // 每次访问需授权的网址时需带上前面的 cookie 作为通行证 // getMethod.setRequestHeader("cookie", tmpcookies.toString()); // 你还可以通过 PostMethod/GetMethod 设置更多的请求后数据 // 例如,referer 从哪里来的,UA 像搜索引擎都会表名自己是谁,无良搜索引擎除外 // postMethod.setRequestHeader("Referer", "http://passport.mop.com/"); getMethod.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); getMethod.setRequestHeader("Referer","http://10.154.13.82:7011/NMMP/login.ilf"); getMethod.setRequestHeader("Accept-Encoding","gzip, deflate"); getMethod.setRequestHeader("Accept-Language","zh-CN,zh;q=0.9"); getMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" ); httpClient.executeMethod(getMethod); statusCode=httpClient.executeMethod(getMethod); System.out.println("模拟登录成功"+statusCode); // 打印出返回数据,检验一下是否成功 // String text = getMethod.getResponseBodyAsString(); InputStream inputStream = getMethod.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String str= ""; while((str = br.readLine()) != null){ stringBuffer .append(str ); } System.out.println("ResponseBody:\n" + stringBuffer.toString()); HttpRequestProxy hrp = new HttpRequestProxy(); Map date = new HashMap(); date.put("jyidApplet", "1"); date.put("codeNumApplet", "1"); date.put("jymxIdApplet", "447"); date.put("patientIdApplet", "1118"); String str1 = hrp.doRequest(dataUrl,date, null, null); System.out.println("sd"+str1); } else { System.out.println("登录失败"); } } catch (Exception e) { e.printStackTrace(); } } } ``` 登录网页源码如下: ``` <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>综合管理系统</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <style type="text/css"> *{ margin:auto; } html,body{ overflow:hidden; width:100%; height:100%; margin:auto; } body{ background:url(/NMMP/common-skins/maintain/images/login_bg_1.0.gif); } #login_panel{ background-image:url(/NMMP/common-skins/maintain/images/login_panel_bg_1.0.png); background-repeat:repeat-x; height:640px; width:100%; text-align:center; position:relative; } #login_input{ background-image:url(/NMMP/common-skins/maintain/images/login_input_1.0.png); background-repeat:no-repeat; width:668px; height:403px; position:relative; } #useraccount{ border:none; position:absolute; left:392px; top:149px; height:24px; width:136px; background-color:#99deff; } #password{ border:none; position:absolute; left:392px; top:183px; height:24px; width:136px; background-color:#99deff; } #login_botton{ position:absolute; left:537px; _left:538px; top:147px; } #message{ position:absolute; left:348px; top:218px; color:#F00; font-size:14px; font-weight:bold; } #technical{ position:absolute; left:375px; top:258px; text-align:left; color:#CCC; font-size:12px; line-height:30px; } #copyright{ position:absolute; bottom:65px; right:0px; color:#CCC; font-size:12px; text-align:right; line-height:20px; } </style> <!--[if IE 6]> <script language="javascript" type="text/javascript" src="/NMMP/common-skins/default/jslib/DD_belatedPNG.js"> </script> <script language="javascript" type="text/javascript"> DD_belatedPNG.fix('#login_panel'); DD_belatedPNG.fix('#login_input'); </script> <![endif]--> </head> <body windowc_onresizez="true"> <div id="login_panel"> <div id="login_input" style="top: 110.5px;"> <form name="form1" action="/NMMP/CtrlUser.action?action=login&amp;surl=jsp/home/main.jsp&amp;furl=jsp/login.jsp" method="post" 360chrome_form_autofill="2"> <input name="useraccount" id="useraccount" style="background-color: rgb(250, 255, 189);" required="true" type="text"> <input name="password" id="password" style="background-color: rgb(250, 255, 189);" required="true" type="password"> <input id="login_botton" type="image" src="/NMMP/common-skins/maintain/images/login_botton.png"> <div id="message"> </div> <!-- div id="technical"><a style="color:orange" href="javascript:void(0)" onclick="resetpwd();">密码重置</a></div--> <div id="copyright">版权所有:</div> </form> </div> </div> <script language="javascript" type="text/javascript"> document.getElementById("login_input").style.top=(document.body.clientHeight-403)/2+"px"; function resetpwd(){ var url = "/NMMP/resetpwdAction.ilf"; window.location.href=url; } </script> </body></html> ```

错误:用户第一次上传时可以正常上传,第二次判断上传就有异常?哪位大神指导一下,小弟万分感谢! ! !

ERROR:upbmsAppid:upbmswl:20161208-16:24:52:jifenhptest:89128126:className:com.hp.upbms.slp.td.transfer.FTPTransfer functionName:doBusiness describe:Exception in FTPTransfer thread when connect to: 10.248.12.2121aiupbms java.net.SocketException: Broken pipe (errno:32) at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:97) at java.net.SocketOutputStream.write(SocketOutputStream.java:141) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at org.apache.commons.net.telnet.TelnetClient._flushOutputStream(TelnetClient.java:77) at org.apache.commons.net.telnet.TelnetOutputStream.flush(TelnetOutputStream.java:137) at java.io.FilterOutputStream.flush(FilterOutputStream.java:123) at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:278) at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122) at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212) at java.io.BufferedWriter.flush(BufferedWriter.java:236) at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:442) at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:520) at org.apache.commons.net.ftp.FTP.cwd(FTP.java:745) at org.apache.commons.net.ftp.FTPClient.changeWorkingDirectory(FTPClient.java:725) at com.hp.upbms.slp.td.transfer.FTPTransfer.doBusiness(FTPTransfer.java:111) at com.hp.upbms.slp.td.transfer.FTPTransfer.run(FTPTransfer.java:55) 这是源码: package com.hp.upbms.slp.td.transfer; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sql.DataSource; import lombok.Setter; import lombok.extern.log4j.Log4j; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.springframework.beans.factory.InitializingBean; import com.hp.upbms.slp.td.TransDownUtil; import com.hp.upbms.slp.td.model.FTPConfig; import com.hp.upbms.slp.td.model.SyncFile; import com.hp.upbms.slp.td.transfer.dao.FtpTransferDaoImpl; /** * <p> * <code>FTPTransfer</code> is used transfer file to cooperator's FTP server. * </p> * <p> * A <code>FTPTransfer</code> thread dealing with a business according to * <code>businessConfig</code>. * </p> * * @author <a href="mailto:liujie.han@hp.com">JetHan</a> */ @Log4j public class FTPTransfer extends Thread implements InitializingBean { @Setter private DataSource dataSource; @Setter private String ftpType = "00"; @Setter private boolean passwordSecurity = false; private static boolean isRunning = true; private final static long ThreadSleepTime = 120000L; private FtpTransferDaoImpl ftpDao = new FtpTransferDaoImpl(); private static List<String> provinceList = new ArrayList<String>(); private Map<String, FTPClient> ftpClients = new HashMap<String, FTPClient>(0); public void afterPropertiesSet() throws Exception { ftpDao.setDataSource(dataSource); provinceList = ftpDao.getProvinceList(); start(); } @Override public void run() { log.info("The FTPTransfer Thread is Started."); while (isRunning) { try { doBusiness(); try { Thread.sleep(ThreadSleepTime); } catch (Exception ex) { log.error("SLEEP(LONG MILLIS)", ex); } } catch (Throwable e) { log.error("The FTPTransfer Thread Throwable:" + e.toString(), e); } } log.info("The FTPTransfer Thread is End."); } private void doBusiness() throws Throwable { try { List<SyncFile> sfs = ftpDao.getNotSyncFile(ftpType); log.info("The Ftp Transfer get data num is "+ sfs.size() + "."); for (SyncFile sf : sfs) { String partnerId = sf.getPartnerId(); if (provinceList.contains(partnerId)) {// 省公司 partnerId = "000"; } FTPConfig fc = ftpDao.getFTPConfig(partnerId, ftpType); if (fc == null || !"00".equals(fc.getFtpStatus())) {// 没有FTP配置及配置信息不可用 ftpDao.updateSyncFileStatus(sf.getFileId(), "03", sf.getSyncTimes() + 1); continue; } String key = fc.getFtpIp() + fc.getFtpPort() + fc.getFtpUsername(); try { FTPClient ftpClient = ftpClients.get(key); if (ftpClient == null) { ftpClient = new FTPClient(); ftpClients.put(key, ftpClient); } if (!ftpClient.isConnected()) { ftpClient.connect(fc.getFtpIp(), Integer.parseInt(fc.getFtpPort())); if(passwordSecurity) { ftpClient.login(fc.getFtpUsername(), TransDownUtil.getDecoder(fc.getFtpPassword())); } else { ftpClient.login(fc.getFtpUsername(), fc.getFtpPassword()); } ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); int reply = ftpClient.getReplyCode(); // If connect failed, try other files. if (!FTPReply.isPositiveCompletion(reply)) { log.error("THE SERVER REPLY " + reply + " ,WHEN CONNECT TO " + key); ftpDao.updateSyncFileStatus(sf.getFileId(), "02", sf.getSyncTimes() + 1); disconnect(ftpClient); continue; } } ftpClient.changeWorkingDirectory(fc.getFilePath()); log.info("The File :" + sf.getFileName() + " transfer start."); FileInputStream in = new FileInputStream(new String(sf.getFilePath().getBytes("GBK"), "ISO-8859-1")); String fileName = new String(sf.getFileName().getBytes("GBK"), "ISO-8859-1"); long startTime = System.currentTimeMillis(); boolean transferResult = ftpClient.storeFile(fileName, in); long stopTime = System.currentTimeMillis(); log.info("The File :" + sf.getFileName() + " transfer finish.Time = " + (stopTime - startTime) + " ms"); if (transferResult) { ftpDao.updateSyncFileStatus(sf.getFileId(), "01", sf.getSyncTimes() + 1); log.info(sf.getFilePath() + " has been transfered to " + key + " successfully"); } else { ftpDao.updateSyncFileStatus(sf.getFileId(), "02", sf.getSyncTimes() + 1); log.info(sf.getFilePath() + " has been transfered to " + key + " failed "); } closeFileStream(in, sf); } catch (Exception ex) { ftpDao.updateSyncFileStatus(sf.getFileId(), "02", sf.getSyncTimes() + 1); log.error("Exception in FTPTransfer thread when connect to: " + key, ex); throw ex; } finally {} } try { Iterator<FTPClient> ite = ftpClients.values().iterator(); while (ite.hasNext()) { FTPClient ftpClient = ite.next(); disconnect(ftpClient); ite.remove(); } ftpClients.clear(); } catch (Exception e) { log.error("Exception in FTPTransfer thread, clear FtpClient info:", e); throw e; } } catch (Throwable ex) { throw ex; } } /** * Close connection of <code>client</code>. * * @param client */ private void disconnect(FTPClient client) { try { if (client != null) { client.logout(); client.disconnect(); } } catch (Throwable e) { log.error("Exception in FTPTransfer thread when disconnect ", e); } } /** * Close file input stream * * @param in * @param sf */ private void closeFileStream(FileInputStream in, SyncFile sf) { try { if (in != null) { in.close(); } } catch (Exception e) { log.error("Exception in FTPTransfer when close file: " + sf.getFilePath() + File.separator + sf.getFileName(), e); } } }

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

删库了,我们一定要跑路吗?

在工作中,我们误删数据或者数据库,我们一定需要跑路吗?我看未必,程序员一定要学会自救,神不知鬼不觉的将数据找回。 在 mysql 数据库中,我们知道 binlog 日志记录了我们对数据库的所有操作,所以 binlog 日志就是我们自救的利器。 接下来就来开启程序员自救之路。 想要自救成功,binlog 这把利器一定要好,在自己之前,我们一定要确定我们有 binlog 这把利器,以下就是确保有 bi...

再不跳槽,应届毕业生拿的都比我多了!

跳槽几乎是每个人职业生涯的一部分,很多HR说“三年两跳”已经是一个跳槽频繁与否的阈值了,可为什么市面上有很多程序员不到一年就跳槽呢?他们不担心影响履历吗? PayScale之前发布的**《员工最短任期公司排行榜》中,两家码农大厂Amazon和Google**,以1年和1.1年的员工任期中位数分列第二、第四名。 PayScale:员工最短任期公司排行榜 意外的是,任期中位数极小的这两家公司,薪资...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

现代的 “Hello, World”,可不仅仅是几行代码而已

作者 |Charles R. Martin译者 | 弯月,责编 | 夕颜头图 |付费下载自视觉中国出品 | CSDN(ID:CSDNnews)新手...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐