Search Results

Search found 35 results on 2 pages for 'linkedhashmap'.

Page 1/2 | 1 2  | Next Page >

  • serialize/deserialize a LinkedHashMap (android) java

    - by user348058
    So i want to pass a LinkedHashMap to an intent. //SEND THE MAP Intent singlechannel = new Intent(getBaseContext(),singlechannel.class); singlechannel.putExtra("db",shows1);//perase to startActivity(singlechannel); //GET THE MAP LinkedHashMap<String,String> db = new LinkedHashMap<String,String>(); db=(LinkedHashMap<String,String>) getIntent().getSerializableExtra("db"); This one Worked Like a charm with HashMap. But with LinkedHashMap i got a problem I got a warning "Type safety: Unchecked cast from Serializable to LinkedHashMap" But i had this warning with HashMap too? Any ideas.Any help is much appreciated Also I just saw this. https://issues.apache.org/jira/browse/HARMONY-6498

    Read the article

  • Difference between HashMap, LinkedHashMap and SortMap in java

    - by theband
    Map m1 = new HashMap(); m1.put("map", "HashMap"); m1.put("schildt", "java2"); m1.put("mathew", "Hyden"); m1.put("schildt", "java2s"); print(m1.keySet()); print(m1.values()); SortedMap sm = new TreeMap(); sm.put("map", "TreeMap"); sm.put("schildt", "java2"); sm.put("mathew", "Hyden"); sm.put("schildt", "java2s"); print(sm.keySet()); print(sm.values()); LinkedHashMap lm = new LinkedHashMap(); lm .put("map", "LinkedHashMap"); lm .put("schildt", "java2"); lm .put("mathew", "Hyden"); lm .put("schildt", "java2s"); print(lm .keySet()); print(lm .values()); What is the difference between these three? I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

    Read the article

  • LinkedHashMap vs HashMap != LinkedList vs ArrayList

    - by Markos Fragkakis
    I have read that LinkedHashMap has faster iteration speed than HashMap because its elements are doubly linked to each other. Additionally, because of this, LinkedHashMap is slower when inserting or deleting elements. Presumably because these links also need to be updated. Although I can see an analogy to LinkedList vs ArrayList, in that the elements of LinkedList are also doubly-linked, I read that it iterates slower than ArrayList, and has faster insertion and deletion times. Why is this? Perhaps I am making a mistake somewhere? Cheers1

    Read the article

  • LRU LinkedHashMap that limits size based on available memory

    - by sanity
    I want to create a LinkedHashMap which will limit its size based on available memory (ie. when freeMemory + (maxMemory - allocatedMemory) gets below a certain threshold). This will be used as a form of cache, probably using "least recently used" as a caching strategy. My concern though is that allocatedMemory also includes (I assume) un-garbage collected data, and thus will over-estimate the amount of used memory. I'm concerned about the unintended consequences this might have. For example, the LinkedHashMap may keep deleting items because it thinks there isn't enough free memory, but the free memory doesn't increase because these deleted items aren't being garbage collected immediately. Does anyone have any experience with this type of thing? Is my concern warranted? If so, can anyone suggest a good approach? I should add that I also want to be able to "lock" the cache, basically saying "ok, from now on don't delete anything because of memory usage issues".

    Read the article

  • Does a HashMap retain the order of its elements on the next read if it is constructed as a LinkedHas

    - by javanix
    Suppose I have a Java method that returns a HashMap object. Because a LinkedHashMap is a subclass of HashMap, I can return a LinkedHashMap from this method just fine. On the next "read" action (no adding/removing/modifying of K/V pairs), would iterating over the keys of the resulting method (which returns a HashMap) go in the same order as the originating LinkedHashMap, even though the HashMap lacks the key links?

    Read the article

  • permute data for a HashMap in Java

    - by tuxou
    hi i have a linkedhashmap and i need to permute (change the key of the values) between 2 random values example : key 1 value 123 key 2 value 456 key 3 value 789 after random permutation of 2 values key 1 value 123 key 2 value 789 key 3 value 456 so here I permuted values between key 2 and key 3 thank you; sample of the code of my map : Map map = new LinkedHashMap(); map =myMap.getLinkedHashMap(); Set key = map.keySet(); for(Iterator it = cles.iterator(); it.hasNext();) { Integer cle = it.next(); ArrayList values = (ArrayList)map.get(cle);//an arrayList of integers int i = 0; while(i < values.size()) { //i donno what to do here i++; } }

    Read the article

  • Using methods on 2 input files - 2nd is printing multiple times - Java

    - by Aaa
    I have the following code to read in text, store in a hashmap as bigrams (with other methods to sort them by frequency and do v. v. basic additive smoothing. I had it working great for one language input file (english) and then I want to expand it for the second language input file (japanese - doens;t matter what it is I suppose) using the same methods but the Japanese bigram hashmap is printing out 3 times in a row with diff. values. I've tried using diff text in the input file, making sure there are no gaps in text etc. I've also put print statements at certain places in the Japanese part of the code to see if I can get any clues but all the print statements are printing each time so I can't work out if it is looping at a certain place. I have gone through it with a fine toothcomb but am obviously missing something and slowly going crazy here - any help would be appreciated. thanks in advance... package languagerecognition2; import java.lang.String; import java.io.InputStreamReader; import java.util.*; import java.util.Iterator; import java.util.List.*; import java.util.ArrayList; import java.util.AbstractMap.*; import java.lang.Object; import java.io.*; import java.util.Enumeration; import java.util.Arrays; import java.lang.Math; public class Main { /** public static void main(String[] args) { //training English ----------------------------------------------------------------- File file = new File("english1.txt"); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String test = null; //test = reader.readLine(); // repeat until all lines are read while ((test = reader.readLine()) != null) { test = test.toLowerCase(); char[] charArrayEng = test.toCharArray(); HashMap<String, Integer> hashMapEng = new HashMap<String, Integer>(bigrams(charArrayEng)); LinkedHashMap<String, Integer> sortedListEng = new LinkedHashMap<String, Integer>(sort(hashMapEng)); int sizeEng=sortedListEng.size(); System.out.println("Total count of English bigrams is " + sizeEng); LinkedHashMap<String, Integer> smoothedListEng = new LinkedHashMap<String, Integer>(smooth(sortedListEng, sizeEng)); //print linkedHashMap to check values Set set= smoothedListEng.entrySet(); Iterator iter = set.iterator ( ) ; System.out.println("Beginning English"); while ( iter.hasNext()) { Map.Entry entry = ( Map.Entry ) iter.next ( ) ; Object key = entry.getKey ( ) ; Object value = entry.getValue ( ) ; System.out.println( key+" : " + value); } System.out.println("End English"); }//end while }//end try catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } //End training English----------------------------------------------------------- //Training japanese-------------------------------------------------------------- File file2 = new File("japanese1.txt"); StringBuffer contents2 = new StringBuffer(); BufferedReader reader2 = null; try { reader2 = new BufferedReader(new FileReader(file2)); String test2 = null; //repeat until all lines are read while ((test2 = reader2.readLine()) != null) { test2 = test2.toLowerCase(); char[] charArrayJap = test2.toCharArray(); HashMap<String, Integer> hashMapJap = new HashMap<String, Integer>(bigrams(charArrayJap)); //System.out.println( "bigrams stage"); LinkedHashMap<String, Integer> sortedListJap = new LinkedHashMap<String, Integer>(sort(hashMapJap)); //System.out.println( "sort stage"); int sizeJap=sortedListJap.size(); //System.out.println("Total count of Japanese bigrams is " + sizeJap); LinkedHashMap<String, Integer> smoothedListJap = new LinkedHashMap<String, Integer>(smooth(sortedListJap, sizeJap)); System.out.println( "smooth stage"); //print linkedHashMap to check values Set set2= smoothedListJap.entrySet(); Iterator iter2 = set2.iterator(); System.out.println("Beginning Japanese"); while ( iter2.hasNext()) { Map.Entry entry2 = ( Map.Entry ) iter2.next ( ) ; Object key = entry2.getKey ( ) ; Object value = entry2.getValue ( ) ; System.out.println( key+" : " + value); }//end while System.out.println("End Japanese"); }//end while }//end try catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader2 != null) { reader2.close(); } } catch (IOException e) { e.printStackTrace(); } } //end training Japanese--------------------------------------------------------- } //end main (inner)

    Read the article

  • Make Java parent class not part of the interface

    - by Bart van Heukelom
    (This is a hypothetical question for discussion, I have no actual problem). Say that I'm making an implementation of SortedSet by extending LinkedHashMap: class LinkedHashSortedMapThing extends LinkedHashMap implements SortedSet { ... } Now programmers who use this class may do LinkedHashMap x = new LinkedHashSortedMapThing(); But what if I consider the extending of LinkedHashMap an implementation detail, and do not want it to be a part of the class' contract? If people use the line above, I can no longer freely change this detail without worrying about breaking existing code. Is there any way to prevent this sort of thing, other than favouring composition over inheritance (which is not always possible due to private/protected members)?

    Read the article

  • Any way to turn off quips in OOWeb?

    - by Misha Koshelev
    http://ooweb.sourceforge.net/tutorial.html Not really a question, but I can't seem to stop writing stuff like this. Maybe someone will find it useful. I know rewriting an HTTP server is not the way to turn off the quips ;) /* Copyright 2010 Misha Koshelev. All Rights Reserved. */ package com.mksoft.common; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.net.ServerSocket; import java.net.Socket; /** * Simple HTTP Server. * * @author Misha Koshelev */ public class HttpServer extends Thread { /* * Constants */ /** * 404 Not Found Result */ protected final static String result404NotFound="<html><head><title>404 Not Found</title></head><body bgcolor='#ffffff'><h1>404 Not Found</h1></body></html>"; /* * Variables */ /** * Port on which HTTP server handles requests. */ protected int port; public int getPort() { return port; } public void setPort(int _port) { port=_port; } /* * Constructors */ public HttpServer(int _port) { setPort(_port); } /* * Helpers */ /** * Errors */ protected void error(String message) { System.err.println(message); System.err.flush(); } /** * Debugging */ protected boolean debugOutput=true; protected void debug(String message) { if (debugOutput) { error(message); } } /** * Lock object */ private Object lock=new Object(); /** * Should we quit? */ protected boolean doQuit=false; /** * Are we done? */ protected boolean areWeDone=false; /** * Process POST request headers */ protected String processPostRequest(String url,LinkedHashMap<String,String> headers,String inputLine) { debug("HttpServer.processPostRequest: url=\""+url); if (debugOutput) { for (String key: headers.keySet()) { debug("HttpServer.processPostRequest: headers."+key+"=\""+headers.get(key)+"\""); } } debug("HttpServer.processPostRequest: inputLine=\""+inputLine+"\""); try { inputLine=new URLDecoder().decode(inputLine,"UTF-8"); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } String[] keyValues=inputLine.split("&"); LinkedHashMap<String,String> post=new LinkedHashMap<String,String>(); for (int i=0;i<keyValues.length;i++) { String keyValue=keyValues[i]; int equals=keyValue.indexOf('='); String key=keyValue.substring(0,equals); String value=keyValue.substring(equals+1); post.put(key,value); } return post(url,headers,post); } /** * Server loop (here for exception handling purposes) */ protected void serverLoop() throws IOException { /* Start server socket */ ServerSocket serverSocket=null; try { serverSocket=new ServerSocket(getPort()); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } Socket clientSocket=null; while (true) { /* Quit if necessary */ if (doQuit) { break; } /* Accept incoming connections */ try { clientSocket=serverSocket.accept(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } /* Read request */ BufferedReader in=null; String inputLine=null; String firstLine=null; String blankLine=null; LinkedHashMap<String,String> headers=new LinkedHashMap<String,String>(); try { in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (true) { if (blankLine==null) { inputLine=in.readLine(); } else { /* POST request, read Content-length bytes */ int contentLength=new Integer(headers.get("Content-Length")).intValue(); StringBuilder sb=new StringBuilder(contentLength); for (int i=0;i<contentLength;i++) { sb.append((char)in.read()); } inputLine=sb.toString(); break; } if (firstLine==null) { firstLine=inputLine; } else if (blankLine==null) { if (inputLine.equals("")) { if (firstLine.startsWith("GET ")) { break; } blankLine=inputLine; } else { int colon=inputLine.indexOf(": "); String key=inputLine.substring(0,colon); String value=inputLine.substring(colon+2); headers.put(key,value); } } } } catch (IOException ioe) { ioe.printStackTrace(); } /* Process request */ String result=null; firstLine=firstLine.replaceAll(" HTTP/.*",""); if (firstLine.startsWith("GET ")) { result=get(firstLine.replaceFirst("GET ",""),headers); } else if (firstLine.startsWith("POST ")) { result=processPostRequest(firstLine.replaceFirst("POST ",""),headers,inputLine); } else { error("HttpServer.ServerLoop: Unhandled request \""+firstLine+"\""); } debug("HttpServer.ServerLoop: result=\""+result+"\""); /* Send response */ PrintWriter out=null; try { out=new PrintWriter(clientSocket.getOutputStream(),true); } catch (IOException ioe) { ioe.printStackTrace(); } if (result!=null) { out.println("HTTP/1.1 200 OK"); } else { out.println("HTTP/1.0 404 Not Found"); result=result404NotFound; } Date now=new Date(); out.println("Date: "+new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(now)); out.println("Content-Type: text/html; charset=UTF-8"); out.println("Content-Length: "+result.length()); out.println(""); out.print(result); /* Clean up */ out.close(); if (in!=null) { in.close(); } clientSocket.close(); } serverSocket.close(); areWeDone=true; synchronized(lock) { lock.notifyAll(); } } /* * Methods */ /** * Run server on port specified in constructor. */ public void run() { try { serverLoop(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } } /** * Process GET request (should be overwritten). */ public String get(String url,LinkedHashMap<String,String> headers) { debug("HttpServer.get: url=\""+url+"\""); if (debugOutput) { for (String key: headers.keySet()) { debug("HttpServer.get: headers."+key+"=\""+headers.get(key)+"\""); } } if (url.equals("/")) { return "<html><head><title>HttpServer GET Test Page</title></head>\r\n"+ "<body bgcolor='#ffffff'>\r\n"+ "<center><h1>HttpServer GET Test Page</h1></center>\r\n"+ "<hr />\r\n"+ "<center><table>\r\n"+ "<form method='post' action='/'>\r\n"+ "<tr><td align=right>Test 1:</td>\r\n"+ " <td><input type='text' name='text 1' value='test me !!! !@#$'></td></tr>\r\n"+ "<tr><td align=right>Test 2:</td>\r\n"+ " <td><input type='text' name='text 2' value='type smthng'></td></tr>\r\n"+ "<tr><td>&nbsp;</td>\r\n"+ " <td align=right><input type='submit' value='Submit'></td></tr>\r\n"+ "</form>\r\n"+ "</table></center>\r\n"+ "<hr />\r\n"+ "<center><a href='/quit'>Shutdown Server</a></center>\r\n"+ "</html>"; } else if (url.equals("/quit")) { quit(); return ""; } else { return null; } } /** * Process POST request (should be overwritten). */ public String post(String url,LinkedHashMap<String,String> headers,LinkedHashMap<String,String> post) { debug("HttpServer.post: url=\""+url+"\""); if (debugOutput) { for (String key: headers.keySet()) { debug("HttpServer.post: headers."+key+"=\""+headers.get(key)+"\""); } } if (url.equals("/")) { String result="<html><head><title>HttpServer Post Test Page</title></head>\r\n"+ "<body bgcolor='#ffffff'>\r\n"+ "<center><h1>HttpServer Post Test Page</h1></center>\r\n"+ "<hr />\r\n"+ "<center><table>\r\n"+ "<tr><th>Key</th><th>Value</th></tr>\r\n"; for (String key: post.keySet()) { result+="<tr><td align=right>"+key+"</td><td align=left>"+post.get(key)+"</td></tr>\r\n"; } result+="</table></center>\r\n"+ "</html>"; return result; } else { return null; } } /** * Wait for server to quit. */ public void waitForCompletion() { while (areWeDone==false) { synchronized(lock) { try { lock.wait(); } catch (InterruptedException ie) { } } } } /** * Shutdown server. */ public void quit() { doQuit=true; } }

    Read the article

  • Is it possible in any Java IDE to collapse the type definitions in the source code?

    - by asmaier
    Lately I often have to read Java code like this: LinkedHashMap<String, Integer> totals = new LinkedHashMap<String, Integer>(listOfRows.get(0)) for (LinkedHashMap<String, Integer> row : (ArrayList<LinkedHashMap<String,Integer>>) table.getValue()) { for(Entry<String, Integer> elem : row.entrySet()) { String colName=elem.getKey(); int Value=elem.getValue(); int oldValue=totals.get(colName); int sum = Value + oldValue; totals.put(colName, sum); } } Due to the long and nested type definitions the simple algorithm becomes quite obscured. So I wished I could remove or collapse the type definitions with my IDE to see the Java code without types like: totals = new (listOfRows.get(0)) for (row : table.getValue()) { for(elem : row.entrySet()) { colName=elem.getKey(); Value=elem.getValue(); oldValue=totals.get(colName); sum = Value + oldValue; totals.put(colName, sum); } } The best way of course would be to collapse the type definitions, but when moving the mouse over a variable show the type as a tooltip. Is there a Java IDE or a plugin for an IDE that can do this?

    Read the article

  • Clustering on WebLogic exception on Failover

    - by Markos Fragkakis
    Hi all, I deploy an application on a WebLogic 10.3.2 cluster with two nodes, and a load balancer in front of the cluster. I have set the <core:init distributable="true" debug="true" /> My Session and Conversation classes implement Serializable. I start using the application being served by the first node. The console shows that the session replication is working. <Jun 17, 2010 11:43:50 AM EEST> <Info> <Cluster> <BEA-000128> <Updating 5903057688359791237S:xxx.yyy.gr:[7002,7002,-1,-1,-1,-1,-1]:xxx.yyy.gr:7002,xxx.yyy.gr:7002:prs_domain:PRS_Server_2 in the cluster.> <Jun 17, 2010 11:43:50 AM EEST> <Info> <Cluster> <BEA-000128> <Updating 5903057688359791237S:xxx.yyy.gr:[7002,7002,-1,-1,-1,-1,-1]:xxx.yyy.gr:7002,xxx.yyy.gr:7002:prs_domain:PRS_Server_2 in the cluster.> When I shutdown the first node from the Administration console, I get this in the other node: <Jun 17, 2010 11:23:46 AM EEST> <Error> <Kernel> <BEA-000802> <ExecuteRequest failed java.lang.NullPointerException. java.lang.NullPointerException at org.jboss.seam.intercept.JavaBeanInterceptor.callPostActivate(JavaBeanInterceptor.java:165) at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:73) at com.myproj.beans.SortingFilteringBean_$$_javassist_seam_2.sessionDidActivate(SortingFilteringBean_$$_javassist_seam_2.java) at weblogic.servlet.internal.session.SessionData.notifyActivated(SessionData.java:2258) at weblogic.servlet.internal.session.SessionData.notifyActivated(SessionData.java:2222) at weblogic.servlet.internal.session.ReplicatedSessionData.becomePrimary(ReplicatedSessionData.java:231) at weblogic.cluster.replication.WrappedRO.changeStatus(WrappedRO.java:142) at weblogic.cluster.replication.WrappedRO.ensureStatus(WrappedRO.java:129) at weblogic.cluster.replication.LocalSecondarySelector$ChangeSecondaryInfo.run(LocalSecondarySelector.java:542) at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201) at weblogic.work.ExecuteThread.run(ExecuteThread.java:173) > What am I doing wrong? This is the SortingFilteringBean: import java.util.HashMap; import java.util.LinkedHashMap; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import com.myproj.model.crud.Filtering; import com.myproj.model.crud.Sorting; import com.myproj.model.crud.SortingOrder; /** * Managed bean aggregating the sorting and filtering values for all the * application's lists. A light-weight bean to always keep in the session with * minimum impact. */ @Name("sortingFilteringBean") @Scope(ScopeType.SESSION) public class SortingFilteringBean extends BaseManagedBean { private static final long serialVersionUID = 1L; private Sorting applicantProductListSorting; private Filtering applicantProductListFiltering; private Sorting homePageSorting; private Filtering homePageFiltering; /** * Creates a new instance of SortingFilteringBean. */ public SortingFilteringBean() { // ********************** // Applicant Product List // ********************** // Sorting LinkedHashMap<String, SortingOrder> applicantProductListSortingValues = new LinkedHashMap<String, SortingOrder>(); applicantProductListSortingValues.put("applicantName", SortingOrder.ASCENDING); applicantProductListSortingValues.put("applicantEmail", SortingOrder.ASCENDING); applicantProductListSortingValues.put("productName", SortingOrder.ASCENDING); applicantProductListSortingValues.put("productEmail", SortingOrder.ASCENDING); applicantProductListSorting = new Sorting( applicantProductListSortingValues); // Filtering HashMap<String, String> applicantProductListFilteringValues = new HashMap<String, String>(); applicantProductListFilteringValues.put("applicantName", ""); applicantProductListFilteringValues.put("applicantEmail", ""); applicantProductListFilteringValues.put("productName", ""); applicantProductListFilteringValues.put("productEmail", ""); applicantProductListFiltering = new Filtering( applicantProductListFilteringValues); // ********* // Home page // ********* // Sorting LinkedHashMap<String, SortingOrder> homePageSortingValues = new LinkedHashMap<String, SortingOrder>(); homePageSortingValues.put("productName", SortingOrder.ASCENDING); homePageSortingValues.put("productId", SortingOrder.ASCENDING); homePageSortingValues.put("productAtcCode", SortingOrder.UNSORTED); homePageSortingValues.put("productEmaNumber", SortingOrder.UNSORTED); homePageSortingValues.put("productOrphan", SortingOrder.UNSORTED); homePageSortingValues.put("productRap", SortingOrder.UNSORTED); homePageSortingValues.put("productCorap", SortingOrder.UNSORTED); homePageSortingValues.put("applicationTypeDescription", SortingOrder.ASCENDING); homePageSortingValues.put("applicationId", SortingOrder.ASCENDING); homePageSortingValues .put("applicationEmaNumber", SortingOrder.UNSORTED); homePageSortingValues .put("piVersionImportDate", SortingOrder.ASCENDING); homePageSortingValues.put("piVersionId", SortingOrder.ASCENDING); homePageSorting = new Sorting(homePageSortingValues); // Filtering HashMap<String, String> homePageFilteringValues = new HashMap<String, String>(); homePageFilteringValues.put("productName", ""); homePageFilteringValues.put("productAtcCode", ""); homePageFilteringValues.put("productEmaNumber", ""); homePageFilteringValues.put("applicationTypeId", ""); homePageFilteringValues.put("applicationEmaNumber", ""); homePageFilteringValues.put("piVersionImportDate", ""); homePageFiltering = new Filtering(homePageFilteringValues); } /** * @return the applicantProductListFiltering */ public Filtering getApplicantProductListFiltering() { return applicantProductListFiltering; } /** * @param applicantProductListFiltering * the applicantProductListFiltering to set */ public void setApplicantProductListFiltering( Filtering applicantProductListFiltering) { this.applicantProductListFiltering = applicantProductListFiltering; } /** * @return the applicantProductListSorting */ public Sorting getApplicantProductListSorting() { return applicantProductListSorting; } /** * @param applicantProductListSorting * the applicantProductListSorting to set */ public void setApplicantProductListSorting( Sorting applicantProductListSorting) { this.applicantProductListSorting = applicantProductListSorting; } /** * @return the homePageSorting */ public Sorting getHomePageSorting() { return homePageSorting; } /** * @param homePageSorting * the homePageSorting to set */ public void setHomePageSorting(Sorting homePageSorting) { this.homePageSorting = homePageSorting; } /** * @return the homePageFiltering */ public Filtering getHomePageFiltering() { return homePageFiltering; } /** * @param homePageFiltering * the homePageFiltering to set */ public void setHomePageFiltering(Filtering homePageFiltering) { this.homePageFiltering = homePageFiltering; } /** * For convenience to view in the Seam Debug page. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(""); sb.append("\n\n"); sb.append("applicantProductListSorting"); sb.append(applicantProductListSorting); sb.append("\n\n"); sb.append("applicantProductListFiltering"); sb.append(applicantProductListFiltering); sb.append("\n\n"); sb.append("homePageSorting"); sb.append(homePageSorting); sb.append("\n\n"); sb.append("homePageFiltering"); sb.append(homePageFiltering); return sb.toString(); } } And this is the BaseManagedBean, inheriting the AbstractMutable. import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage.Severity; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.ArrayUtils; import org.jboss.seam.core.AbstractMutable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.myproj.common.exceptions.WebException; import com.myproj.common.util.FileUtils; import com.myproj.common.util.StringUtils; import com.myproj.web.messages.Messages; public abstract class BaseManagedBean extends AbstractMutable { private static final Logger logger = LoggerFactory .getLogger(BaseManagedBean.class); private FacesContext facesContext; /** * Set a message to be displayed for a specific component. * * @param resourceBundle * the resource bundle where the message appears. Either base or * id may be used. * @param summaryResourceId * the id of the resource to be used as summary. For the detail * of the element, the element to be used will be the same with * the suffix {@code _detail}. * @param parameters * the parameters, in case the string is parameterizable * @param severity * the severity of the message * @param componentId * the component id for which the message is destined. Note that * an appropriate JSF {@code <h:message for="myComponentId">} tag * is required for the to appear, or alternatively a {@code * <h:messages>} tag. */ protected void setMessage(String resourceBundle, String summaryResourceId, List<Object> parameters, Severity severity, String componentId, Messages messages) { FacesContext context = getFacesContext(); FacesMessage message = messages.getMessage(resourceBundle, summaryResourceId, parameters); if (severity != null) { message.setSeverity(severity); } context.addMessage(componentId, message); } /** * Copies a byte array to the response output stream with the appropriate * MIME type and content disposition. The response output stream is closed * after this method. * * @param response * the HTTP response * @param bytes * the data * @param filename * the suggested file name for the client * @param mimeType * the MIME type; will be overridden if the filename suggests a * different MIME type * @throws IllegalArgumentException * if the data array is <code>null</code>/empty or both filename * and mimeType are <code>null</code>/empty */ protected void printBytesToResponse(HttpServletResponse response, byte[] bytes, String filename, String mimeType) throws WebException, IllegalArgumentException { if (response.isCommitted()) { throw new WebException("HTTP response is already committed"); } if (ArrayUtils.isEmpty(bytes)) { throw new IllegalArgumentException("Data buffer is empty"); } if (StringUtils.isEmpty(filename) && StringUtils.isEmpty(mimeType)) { throw new IllegalArgumentException( "Filename and MIME type are both null/empty"); } // Set content type (mime type) String calculatedMimeType = FileUtils.getMimeType(filename); // not among the known ones String newMimeType = mimeType; if (calculatedMimeType == null) { // given mime type passed if (mimeType == null) { // none available put default mime-type newMimeType = "application/download"; } else { if ("application/octet-stream".equals(mimeType)) { // small modification newMimeType = "application/download"; } } } else { // calculated mime type has precedence over given mime type newMimeType = calculatedMimeType; } response.setContentType(newMimeType); // Set content disposition and other headers String contentDisposition = "attachment;filename=\"" + filename + "\""; response.setHeader("Content-Disposition", contentDisposition); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "max-age=30"); response.setHeader("Pragma", "public"); // Set content length response.setContentLength(bytes.length); // Write bytes to response OutputStream out = null; try { out = response.getOutputStream(); out.write(bytes); } catch (IOException e) { throw new WebException("Error writing data to HTTP response", e); } finally { try { out.close(); } catch (Exception e) { logger.error("Error closing HTTP stream", e); } } } /** * Retrieve a session-scoped managed bean. * * @param sessionBeanName * the session-scoped managed bean name * @return the session-scoped managed bean */ protected Object getSessionBean(String sessionBeanName) { Object sessionScopedBean = FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get(sessionBeanName); if (sessionScopedBean == null) { throw new IllegalArgumentException("No such object in Session"); } else { return sessionScopedBean; } } /** * Set a session-scoped managed bean * * @param sessionBeanName * the session-scoped managed bean name * @return the session-scoped managed bean */ protected boolean setSessionBean(String sessionBeanName, Object sessionBean) { Object sessionScopedBean = FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get(sessionBeanName); if (sessionScopedBean == null) { FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put(sessionBeanName, sessionBean); } else { throw new IllegalArgumentException( "This session-scoped bean was already initialized"); } return true; } /** * For testing (enables mock of FacesContext) * * @return the faces context */ public FacesContext getFacesContext() { if (facesContext == null) { return FacesContext.getCurrentInstance(); } return facesContext; } /** * For testing (enables mocking of FacesContext). * * @param aFacesContext * a - possibly mock - faces context. */ public void setFacesContext(FacesContext aFacesContext) { this.facesContext = aFacesContext; } }

    Read the article

  • When I try to redefine a variable, I get an index out of bounds error

    - by user2770254
    I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error. public static void main(String args[]) { LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>(); Scanner scan = new Scanner(System.in); ArrayList<Integer> values = new ArrayList<>(); ArrayList<String> variables = new ArrayList<>(); while(scan.hasNextLine()) { String line = scan.nextLine(); String[] tokens = line.split(" "); if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var")) { int value = 0; for(int i=0; i<tokens.length; i++) { if(tokens.length==3) { value = Integer.parseInt(tokens[2]); System.out.printf("%5d\n",value); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(tokens[i].charAt(0) == '+') { value = addition(tokens, value); System.out.printf("%5d\n",value); variables.add(tokens[0]); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(i==tokens.length-1 && tokens.length != 3) { System.out.println("No operation"); break; } } map.put(tokens[0], value); } if(Character.isDigit(tokens[0].charAt(0))) { int value = 0; if(tokens.length==1) { System.out.printf("%5s\n", tokens[0]); } else { value = addition(tokens, value); System.out.printf("%5d\n", value); } } if(line.equals("clear")) { clear(map); } if(line.equals("var")) { variableList(variables, values); } } } public static int addition(String[] a, int b) { for(String item : a) { if(Character.isDigit(item.charAt(0))) { int add = Integer.parseInt(item); b = b + add; } } return b; } public static void clear(LinkedHashMap<String,Integer> b) { b.clear(); } public static void variableList(ArrayList<String> a, ArrayList<Integer> b) { for(int i=0; i<a.size(); i++) { System.out.printf("%5s: %d\n", a.get(i), b.get(i)); } } I included the whole code because I'm not sure where the error is arising from.

    Read the article

  • Call HashMap from jsp EL ?

    - by Parhs
    Here is my Entity Class public enum UnitType { HOSPITAL, HEALTHCENTER } public static LinkedHashMap<UnitType, String> unitType = new LinkedHashMap<UnitType, String>() { { put(UnitType.HEALTHCENTER, "???t?? ??e?a?"); put(UnitType.HOSPITAL, "??s???µe??"); } }; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String address; @Column(columnDefinition = "TEXT") private String info; @Enumerated(EnumType.STRING) private UnitType type; At my jsp <c:forEach var="unit" items="${requestScope.units}"> <tr> <td>${unit.id}</td> <td>${unit.name}</td> <td>${unit.address}</td> <td>??!?</td> <td><a href="#">?e??ss?te?a</a></td> </tr> </c:forEach> How can i place the text value of the enum at ??!? .. Any idea? Tried some ways but nothing worked..

    Read the article

  • java hashmap array to double array

    - by Tweety
    Hi, I declared LinkedHashMap<String, float[]> and now I want to convert float[] values into double[][]. I am using following code. LinkedHashMap<String, float[]> fData; double data[][] = null; Iterator<String> iter = fData.keySet().iterator(); int i = 0; while (iter.hasNext()) { faName = iter.next(); tValue = fData.get(faName); //data = new double[fData.size()][tValue.length]; for (int j = 0; j < tValue.length; j++) { data[i][j] = tValue[j]; } i++; } When I try to print data System.out.println(Arrays.deepToString(data)); it doesn't show the data :( I tried to debug my code and i figured out that I have to initialize data outside the while loop but then I don't know the array dimensions :( How to solve it? Thanks

    Read the article

  • how to skip first 3 row of text file.

    - by Dilantha Chamal
    hey when i reading the text file using java, how can i skip first 3 rows of the text file. Show me how to do that. public class Reader { public static void main(String[] args) { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream("sample.txt"))); Map<String, Integer result = new LinkedHashMap<String, Integer(); Map<String, Integer result2 = new LinkedHashMap<String, Integer(); while (reader.ready()) { String line = reader.readLine(); /split a line with spaces/ String[] values = line.split("\s+"); /set a key date\tanimal/ String key = values[0] + "\t" + values[1]; int sum = 0; int count = 0; /get a last counter and sum/ if (result.containsKey(key)) { sum = result.get(key); count = result2.get(key); } else{ } /increment sum a count and save in the map with key/ result.put(key, sum + Integer.parseInt(values[2])); result2.put(key, count + 1); } /interate and print new output/ for (String key : result.keySet()) { Integer sum = result.get(key); Integer count = result2.get(key); System.out.println(key + " " + sum + "\t" + count); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

    Read the article

  • Is there a data structure for this type of list/map?

    - by Nick
    Perhaps there's a name for what I want, but I'm not aware of it. I need something similar to a LinkedHashMap in Java, but where it returns the 'previous' value if there's no value at the specified key. That is, I have a list of objects stored by an integer key (which is in units of time in my case): ; key->value 10->A 15->B 20->C So, if I were to query for a value for key 0-9, it would return null. The special part is if I queried for something 10 <= i <= 14 it would return A. Or, for i = 20, it would return C. Is there a data structure for this?

    Read the article

  • Concurrent Linked HashMap java

    - by Nilesh
    Please help me use/create Concurrent LinkedHashMap. As per my belief, if I use Collections.synchronizedMap(), I would have to use synchronized blocks for getter/setter. If I use ConcurrentSkipListMap, is there any way to implement a Comparator to store sequentially. I would like to use java's built in instead of third party packages. Thanks

    Read the article

  • Java Data Structure

    - by Joe
    Hi there, I'm looking for a data structure that will act like a Queue so that I can hava First In First Out behaviour, but ideally I would also be able to see if an element exists in that Queue in constant time as you can do with a HashMap, rather than the linear time that you get with a LinkedList. I thought a LinkedHashMap might do the job, but although I could make an iterator and just take and then remove the first element of the iteration to produce a sort of poll() method, I'm wondering if there is a better way. Many thanks in advance

    Read the article

  • How to mock/stub calls to message taglib in Grails controller

    - by Dave
    I've got a Grails controller which relies on the message taglib to resolve an i18n message: class TokenController { def passwordReset = { def token = DatedToken.findById(params.id); if (!isValidToken(token, params)) { flash.message = message(code: "forgotPassword.reset.invalidToken") redirect controller: 'forgotPassword', action: 'index' return } render view:'/forgotPassword/reset', model: [token: token.token] } } I've written a unit test for the controller: class TokenControllerTests extends ControllerUnitTestCase { void testPasswordResetInvalidTokenRedirect() { controller.passwordReset() assert... } } Since the message taglib is called in the controller I get a MissingMethodException: groovy.lang.MissingMethodException: No signature of method: TokenController.message() is applicable for argument types: (java.util.LinkedHashMap) values: [[code:forgotPassword.reset.invalidToken]] Does anyone know the best way to get around this issue in a unit test? Ideally I would like to perform assertions on the message but right now I'd be happy if the test just ran! Thanks

    Read the article

  • Can a grails controller extend from a base class? How to make it so grails doesn't blow up?

    - by egervari
    I wrote a base class to help build my controllers more quickly and to remove duplication. It provides some helper methods, default actions and some meta programming to make these things easier to build. One of those methods in the base class is like this: def dynamicList(Class clazz) { def model = new LinkedHashMap() model[getMapString(clazz) + "s"] = list(clazz) model[getMapString(clazz) + "sTotal"] = count(clazz) model } The action that calls it, also in the base class, is this: def list = { dynamicList(clazz) } Unfortunately, when I go to list action in the controller subclass that inherits the base class when my application is deployed, I get this exception: groovy.lang.MissingMethodException: No signature of method: groovy.lang.MissingMethodException.dynamicList() is applicable for argument types: (java.lang.Class) values: [class project .user.User] at project.user.UserController$_closure1.doCall(UserController.groovy:18) at project.user.UserController$_closure1.doCall(UserController.groovy) at java.lang.Thread.run(Thread.java:619) How can I hit grails over the head and just tell it do what I want it to do? My controller unit tests run just fine, so grails' run-time is totally at fault :/ Ken

    Read the article

  • Accessing the next 3 element values in a Map knowing the key.

    - by Rachel
    I have java.util.LinkedHashMap with Integer as Key and Character as Value. I know the key of the element i want to access. In addition to the element value for the key, i also want to retrieve the next 3 element values so that i can append all the 4 element values and form a string with 4 chars. I am asking for something like how we will do in a java.util.List. Is this feasible by any means in a Map/ordered map? Please suggest any other data structure that can help me achieve this. I am using Java 6.

    Read the article

1 2  | Next Page >