Menu
  • HOME
  • TAGS

count items in a column vaadin

java,vaadin

Columns don't contain items, Rows contain items. You can set the visible columns by passing a array to the setVisibleColumns methos of the Table. It could also be a idea, to just colapse the column, not hiding it... Determining if all values of this colum are empty should be simple...

How to block writes to standard output in java (System.out.println())

java,logging,stdout

If you can identify the thread you want to "mute" reliably somehow (e.g. by name), you can setOut to your own stream which will only delegate the calls to the actual System.out if they don't come from the muted thread.

Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

java,spring,jms,spring-boot,spring-jms

The big difference between your code and the example is in the XML config example that myTargetConnectionFactory is actually a bean managed by Spring. You aren't doing that. You are just creating a new object Spring doesn't know about. The magic happens when setting the targetConnectionFactory of myConnectionFactory. Even though...

Can I install 2 or more Android SDK when using Eclipse

java,android,eclipse,sdk,versions

There shouldn't be any problem if you use the latest SDK version ; actually, this is recommended. However, make sure to set the correct "Target SDK", i.e. the highest android version you have successfully tested your app with, and the "Minimum Required SDK" as well....

Postgresql Update JDBC

java,postgresql,jdbc

You shouldn't build SQL by putting your variables directly via string concatenation. What happens here is that with 11, your SQL becomes: set last=11 Which is valid SQL (using 11 as a integer literal), while with xx it becomes: set last=xx There are no quotes, so the SQL means you're...

Form submit portlet with Spring MVC

java,jsp,spring-mvc,liferay,portlet

Which version of Liferay you are using? if it is > 6.2 GA1 Then in your liferay-portlet.xml file, please add this attribute and recompile and test again. <requires-namespaced-parameters>false</requires-namespaced-parameters> Liferay adds namespace to the request parameters by default. You need to disable it. ...

Android Implicit Intent for Viewing a Video File

java,android,android-intent,uri,avd

Change your onClick method to below code. You should give the option to choose the external player. @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("https://youtu.be/jxoG_Y6dvU8"), "video/*"); startActivity(Intent.createChooser(intent, "Complete action using")); } ...

BitmapFont class does not have getBound(String) method

java,android,libgdx

After the API 1.5.6 we have a different way to get the String bound. try this GlyphLayout layout = new GlyphLayout(); layout.setText(bitmapFont,"text"); float width = layout.width; float height = layout.height; and it's not recommended to create new GlyphLayout on each frame, create once and use it. ...

@RestController throws HTTP Status 406

java,spring,rest,maven

The issue is with the dependencies that you have in pom.xml file. In Spring 4.1.* version the pom.xml dependency for Jackson libraries should include these: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1.1</version> </dependency> You...

A beginner questions about printf, java

java,string,printf

I'm sad that this question hasn't been answered, and upon that, I can't upvote it from it's -8 cause I don't have enough reputation. It seems downvoting is getting too unwarranted here. OP is just looking for an answer, which can be answered here and found online, he has tried...

Iterating over a map and putting its values in java

java,guava

It Should be a loop inside loop for column and row final Table<String, String, List<String>> values = HashBasedTable.create(); values.put("ton bon", "currency", Lists.newArrayList("ccdd","rode1","cwey","Certy")); values.put("ton bon", "racy", Lists.newArrayList("wqadd","werde","ihtr","ytre")); Map<String, List<String>> row = values.row("ton bon"); Map<String, String> fmap = new HashMap<String, String>(); System.out.println("Key\tValue"); for(String columnKey:row.keySet()) { List<String> rowValues =...

Android String if-statement

java,android,string

Correct me if I'm wrong. If you're saying that your code looks like this: new Thread(new Runnable() { public void run() { // thread code if (ready.equals("yes")) { // handler code } // more thread code }).start(); // later on... ready = "yes"; And you're asking why ready = "yes"...

Using user input value to display a specific object from an array list

java,arraylist

Unfortunately, you need a custom method for this with a while loop: public int getIndexWithName(List<Animal> animals, String name){ for (int index = 0; index < animals.size(); index++){ if (name.equals(animals.get(index).getName())){ return index; } } return -1; } And use this: int index = getIndexWithName(animalList, select); //Do some validation check if (index...

byte array to string and inverse : recoverded byte array is NOT match to original byte array in Java

java,string,bytearray

You cannot convert an arbitrary sequence of bytes to String and expect the reverse conversion to work. You will need to use an encoding like Base64 to preserve an arbitrary sequence of bytes. (This is available from several places -- built into Java 8, and also available from Guava and...

Java.util.logger new file every day

java,logging

Java.util.logging does not support rotating on a daily basis, see this bug report: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6350749 Alternatively, you could use logback, log4j or log4j2 and slf4j to tunnel JUL (see http://www.slf4j.org/legacy.html#jul-to-slf4j). All of the mentioned frameworks support date-based file rotation. HTH, Mark...

how to call Java method which returns any List from R Language? [on hold]

java,r,rjava

You can do it with rJava package. install.packages('rJava') library(rJava) .jinit() jObj=.jnew("JClass") result=.jcall(jObj,"[D","method1") Here, JClass is a Java class that should be in your ClassPath environment variable, method1 is a static method of JClass that returns double[], [D is a JNI notation for a double array. See that blog entry for...

Logging operations in lightadmin

java,spring,logging,lightadmin

You can use the class AbstractRepositoryEventListener like it's show on the LightAdmin documentation here Add you logger insertion by overiding onAfterSave, onAfterCreate and onAfterDelete into your own RepositoryEventListener. After you just need to register your listener like this public class YourAdministration extends AdministrationConfiguration<YourObject> { public EntityMetadataConfigurationUnit configuration(EntityMetadataConfigurationUnitBuilder configurationBuilder) { return...

Implementing enum-based singleton

java,enums,singleton

The actual enum behavior of instatiating the instance doesn't have an issue with thread safety. However, you will need to make sure that the instance state itself is thread-safe. The interactions with the fields and methods of Application are the risk--using either careful synchronization and locking, or purely concurrent data...

Interpreting hex dump of java class file

java,class,hex

The 000000b0 is not part of the data. It's the memory address where the following 16 bytes are located. The two-digit hex numbers are the actual data. Read them from left to right. Each row is in two groups of eight, purely to asist in working out memory addresses etc....

Selenium catch popup on close browser

java,selenium,browser

Instead of using driver.quit() to close the browser, closing it using the Actions object may work for you. This is another way to close the browser using the keyboard shortcuts. Actions act = new Actions(driver); act.sendKeys(Keys.chord(Keys.CONTROL+"w")).perform(); Or, if there are multiple tabs opened in driver window: act.sendKeys(Keys.chord(Keys.CONTROL,Keys.SHIFT+"w")).perform(); ...

Get the min and max value of several items with Comparable

java

You should not let BehaviourItem implement Comparable as it doesn’t have a natural order. Instead, implement different Comparators for the different properties. Note that in Java 8, you can implement such a Comparator simply as Comparator<BehaviourItem> orderBySpeed=Comparator.comparingInt(BehaviourItem::getSpeed); which is the equivalent of Comparator<BehaviourItem> orderBySpeed=new Comparator<BehaviourItem>() { public int compare(BehaviourItem a, BehaviourItem...

Get document on some condition in elastic search java API

java,elasticsearch,elasticsearch-plugin

When indexing documents in this form, Elasticsearch will not be able to parse those strings as dates correctly. In case you transformed those strings to correctly formatted timestamps, the only way you could perform the query you propose is to index those documents in this format { "start": "2010-09", "end":...

Android set clickable text to go one fragment to another fragment

java,android,android-fragments,spannablestring

If LoginActivity is a fragment class then it would be okay is you use setOnClickListener on textview. But for fragment change you have to change Intent to fragmentTransaction, Use something like, textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction().replace(R.id.container, new LoginActivity() ).addToBackStack("").commit(); }); But, if you want to...

Dynamic creation of objects vs storing them as fields

java,performance,object

There won't be any difference, since you've only changed the scope of the variables. Since you're not using the variables outside of the scope, the generated bytecode will be identical as well (you can try it out with javap). So use the second style for clarity. Edit: In fact if...

Spring Resttemplate login fails

java,spring,spring-mvc,spring-security,csrf

You seem to have upgraded Spring Security to 4.x as well (evidenced by xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd). Unfortunately, Spring Security 4.x is not a drop-in replacement for 3.x. You will need to review the Official Migration Guide for configuration elements that need to be tweaked. However, some of the ones that stand...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

java,spring,jsp,spring-mvc

Say you have a jsp test.jsp under /WEB-INF/jsp/reports From your controller return @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "reports/test"; } ...

possibly lossy conversion from int to byte

java,javax.comm

If you look at the error message: Main.java:10: error: incompatible types: possible lossy conversion from int to byte static byte[] bytearray = {0x02, 0x08, 0x16, 0x0, 0x00, 0x33, 0xC6, 0x1B}; ^ There is a small caret pointing to the value 0xC6. The reason for the issue is that java's byte...

Create and initialize a singleton with Guice [duplicate]

java,guice

You can use the provider interface public class StorageProxyProvider implements Provider<StorageProxy> { public StorageProxy get() { StorageProxy storageProxy = new StorageProxy(); storageProxy.init(); return storageProxy; } } public class StorageProxyModule extends AbstractModule { protected void configure() { bind(StorageProxy.class).toProvider(StorageProxyProvider.class).in(Singleton.class); } } A working example: public class StorageProxyProvider implements Provider<StorageProxy> { public StorageProxy...

Relationship between a package statement and the directory of a .java file?

java,package

Consider a package hierarchy folder1/hi. folder1 contains B.java and hi contains A.java. So B.java is in folder1 and A.java is in a folder named hi. So far so good. B.java looks like this : package hi.a12.pkg; public class B { } Oops. B.java says that it is in a...

Javadoc: Do parameter and return need an explicit type description

java,types,javadoc

No, there's no need, the JavaDoc tool parses the Java code and gets the types from there. This article on the Oracle Java site may be useful: How to Write Doc Comments for the Javadoc Tool From the @param part of that article: The @param tag is followed by the...

Get the value of the last inserted record

java,jdbc

You may try this query: select stop_name from behaviour where created_at in (select max(created_at) from behaviour) ...

ffmpeg problems (mpeg1video -> ?)

java,ffmpeg

SEVERE: DDCS - configuration: --extra-ldflags=-L/home/user/trunk/cpp_src/ffmpeg-source/libvpx --extra-ldflags=-L/home/user/trunk/cpp_src/ffmpeg-source/x264 --extra-cflags=-I/home/user/trunk/cpp_src/ffmpeg-source/x264 --extra-cflags=-I/home/user/trunk/cpp_src/ffmpeg-source/libvpx --enable-libvpx --enable-libx264 --enable-gpl --yasmexe=/home/user/trunk/cpp_src/ffmpeg-source/yasm/yasm Your ffmpeg is not compiled with libtheora support, so you can't encode to ogg/theora....

Assigning text file data to java variable

java

This worked for me: String str = "CN=COUD111235,OU=Workstations,OU=Mis,OU=Accounts,DC=FL,DC=NET"; String regex = "CN=([^,]*),"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); m.find(); String computerName = m.group(1); Full example referencing your code: import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[]...

Exception in thread “main” java.util.InputMismatchException: For input string: “1234567891011”

java

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range. Integer.MIN_VALUE: -2147483648 Integer.MAX_VALUE: 2147483647 Instead of int use long long z = sc.nextLong(); ...

implement a method that takes 3 boolean args

java

I think the simplest way would be to make your booleans to int values and add them up. private static boolean odd(boolean x, boolean y, boolean z) { int sum = 0; if(x) sum++; if(y) sum++; if(z) sum++; // check if its odd. return sum % 2 != 0; }...

why java API prevents us to call add and remove together?

java,list,collections,listiterator

You're reading the wrong documentation: you should read ListIterator's javadoc. It says: Throws: ... IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous Now, if you want a reason, it's rather simple. You're playing...

Mysterious claim of a missing { in eclipse

java,eclipse

In Java, you cannot write executable statements directly in class.So this is syntactically wrong: for(int i=0; i<10; i++) { this.colorList[i] = this.allColors[this.r.nextInt(this.allColors.length)]; } Executable statements can only be in methods/constructors/code blocks...

Numeric literals in Java - octal? [duplicate]

java,literals,octal

-0777 is treated by the compiler as an octal number (base 8) whose decimal value is -511 (-(64*7+8*7+7)). -777 is a decimal number.

Give port number and passed parameters in WSO2

java,api,wso2,wso2-am,api-manager

The Test button will send HTTP OPTION request to the endpoint, and if the endpoint supports HTTP OPTION request, then it is shown as valid. As far as your backend point support the HTTP method you need, you don't need to worry about this Test button against the endpoint....

Why ever use CachedGauage in Dropwizard Metrics?

java,metrics,dropwizard,codahale-metrics

Quoting the same link you added: Cached Gauges A cached gauge allows for a more efficient reporting of values which are expensive to calculate What if your metric takes around two seconds seconds to calculate, or even minutes? Would you calculate every time the user request the data? Makes sense...

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) doesn't work

java,jpa,glassfish,ejb-3.0

deleteEmployee method is not wrapped into a new transaction because you are referencing method on this. What you can do is to inject reference to the facade itself and then call deleteEmployee method on it (it should be public). More or less something like this: @Stateless public class MyFacade {...

Broken pipe error when executing Android method more than once?

java,android,illegalstateexception,broken-pipe

When you execute the command os.writeBytes("exit\n"); this ends your su session. The su process ends itself and the pipe your are using for writing commands to the su shell gets broken. Therefore if you want to execute another command you have to restart a new su session or do not...

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2

You can simply create an Entity, that's mapping the database view: @Entity public class CustInfo { private String custMobile; private String profession; private String companyName; private Double annualIncome; } Make sure you include an @Id in your view as well, if that's an updatable view. Then you can simply use...

Java dice roll with unexpected random number

java,if-statement

else { System.out.println(diceNumber); } You are printing the address of diceNumber by invoking its default toString() function in your else clause. That is why you are getting the [email protected] The more critical issue is why it gets to the 'else' clause, I believe that is not your intention. Note: In...

SOAP Client, Following an example

java,soap,saaj

Actually you can generate class with soap ui. And your program can easily call the service using the class created without construct your own request header and body But you need some library. Example java jdk comes with jax-ws lib tutorial: http://www.soapui.org/soap-and-wsdl/soap-code-generation.html...

Reading and modifying the text from the text file in Java

java

I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash. The method reads the file and writes it straight out to...

Instantiate web service

java,jaxb,wsdl

The way you are trying to create the client is correct, be carreful with the classes that you use, but the general idea is correct. This is a good tutorial for creating a web service and the client in that way. Another way is using the wsconsume or wsimport tools....

Get network interfaces on remote machine

java,network-programming

No, we cannot by definition. The IP address is needed to hide the mac address from external world. To retrieve it you definitely need some code running on that machine. It means that you need some kind of agent. You can either implement it in Java or use platform specific...

Join files using Apache Spark / Spark SQL

java,apache-spark,apache-spark-sql

If you use plain spark you can join two RDDs. let a = RDD<Tuple2<K,T>> let b = RDD<Tuple2<K,S>> RDD<Tuple2<K,Tuple2<S,T>>> c = a.join(b) This produces an RDD of every pair for key K. There are also leftOuterJoin, rightOuterJoin, and fullOuterJoin methods on RDD. So you have to map both datasets to...

Swing regular expression for phone number validation

java,regex

To only allow digits, comma and spaces, you need to remove (, ) and -. Here is a way to do it with Matcher.find(): Pattern pattern = Pattern.compile("^[0-9, ]+$"); ... if (!m.find()) { evt.consume(); } And to allow an empty string, replace + with *: Pattern pattern = Pattern.compile("^[0-9, ]*$");...

type conversion if flex

java,actionscript-3,flex

You try to cast data type mx.collections:IList to UI component type spark.components:List, which of course leads to exception. Try to follow the error message hint and use mx.collections:IList: screenList.addAll(event.result as IList); ...

Using world coordinates

java,libgdx

You shouldn't use constant a pixel-to-unit conversion, as this would lead to different behavior on different screen sizes/resolutions. Also don't forget about different aspect ratios, you also need to take care about them. The way you should solve this problem is using Viewports. Some of them support virtual screen sizes,...

Getting particular view from expandable listview

java,android,listview,android-fragments,expandablelistview

You shouldn't pass your view item form a fragment to an other. You should retrieve the object associated with your group view, pass this object to your second/edition fragment. You can use setTargetFragment(...) and onActivityResult(...) to send the modified text from your second to your first fragment. And then you...

Return value -Java API design VS. C API

java,api

One major difference is that Java had exceptions, and exception handling, from the start. That means there is no need to return "SUCCESS". If it returns at all, rather than throwing an exception, it was successful. Java does not have pass-by-reference. What it does have is pointers. When you call...

Change the “about this” window on mac app

java,osx,deployment

If your application is an .app bundle then it should have an info.plist. Inside the info.plist will normally contain version information that should display the version number: <key>CFBundleShortVersionString</key> <string>2.0.0</string> Typically the version information here is populated in places that call for it (eg. About). To change the name that would...

How to check if an ExecutionResult is empty in Neo4j

java,neo4j

An execution result is essentially an iterator of a map, its type definition is something like: Iterable<Map<String,Object>> So you can easily just do: result.iterator().hasNext(); I think that its strictly a ResourceIterator, so if you get an iterator you are supposed to close it if you don't exhaust it. Check the...

Java - Enforce TextField Format - UX - 00:00:00;00

java,regex,user-interface

How about using JFormattedTextField with MaskFormatter. JFormattedTextField formattedTextField = new JFormattedTextField("00:00:00;00"); try { MaskFormatter maskFormatter = new MaskFormatter("##:##:##;##"); maskFormatter.install(formattedTextField); } catch (ParseException e) { e.printStackTrace(); } More info at http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html Demo code: JFrame frame = new JFrame(""); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); JFormattedTextField...

custom arraylist get distinct

java,android

It's not possible to do this using only the ArrayList. Either implement your own method which can be as simple as: private List<mystatistik> getAllUniqueEnemies(List<mystatistik> list){ List<mystatistik> uniqueList = new ArrayList<mystatistik>(); List<String> enemyIds = new ArrayList<String>(); for (mystatistik entry : list){ if (!enemyIds.contains(entry.getEnemyId())){ enemyIds.add(entry.getEnemyId()); uniqueList.add(entry); } } return uniqueList; } Or...

WebDriver can't get dropdown menu element (Java)

java,selenium,webdriver,junit4

Your ID is dynamic, so you can't use it. Select will not work in your case, you just need to use two clicks WebElement dropdown = driver.findElement(By.xpath("//div[@class='select-pad-wrapper AttributePlugin']/input")); dropdown.click(); WebElement element = driver.findElement(By.xpath("//div[@class='select-pad-wrapper AttributePlugin']/div/ul/li[text()='Image']")); element.click(); ...

Finding embeded xpaths in a String

java,regex

Use {} instead of () because {} are not used in XPath expressions and therefore you will not have confusions.

Serializing a java bean into a cookie: Is it bad?

java,json,cookies

I guess the answer depends on your answer to these questions: Since you can never trust ANYTHING that comes in a client request, are there any harmful effects that could come by a hacker spoofing the pojo value? By sending the object to the client, does this expose any internal...

Comparasion of Integer.equals() and Objects.equals()

java,testing,equals

Because the JIT kicks in, and detects that Random.nextInt() and equals() are two methods that are often called, and that optimizing them is thus useful. Once the byte-code is optimized and transformed to native code, its execution is faster. Note that what you're measuring is probably more Random.nextInt() than equals()....

Using Class names as identifiers

java

You can use a fully qualified name, for example, java.lang.String.length()

Getting a mouse position with JavaFX and Event

java,javafx

You need to use the JavaFx MouseEvent. Currently you are trying to use the Java.awt MouseEvent Try importing only Java libraries from Javafx and not awt so you can avoid having the wrong type. Once you fix that, the methods getX() and getY() should give you the position. (Or depending...

How to do custom rounding of numbers in Java?

java,rounding

Math.floor(x+0.7) should do it. This should work for an arbitrary mantissa. Just add the offset to the next integer to your value and round down. The rounding is done by floor. Here is what the java API says to floor: Returns the largest (closest to positive infinity) double value that...

error: cannot find symbol class AsyncCallWS Android

java,android,web-services

On the link you post, I see a class like below. Create this class in your project before using it. private class AsyncCallWS extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { Log.i(TAG, "doInBackground"); getFahrenheit(celcius); return null; } @Override protected void onPostExecute(Void result) { Log.i(TAG, "onPostExecute"); tv.setText(fahren +...

Why do I get different results on variable value?

java

Instance variables are declared inside a class. not within a method. class A { private int price; //instance variable private String name; //instance variable } And instance variables always get a default value( integers 0, floating points 0.0, booleans false, String / references null). Local variables are declared within a...

What does '<< ' mean ? And what this code mean?

java

My guess is that it approximates PI with PI = doCalculatePi(0)+doCalculatePi(1)+doCalculatePi(2)+... Just a guess. Trying this double d = 0; for(int k = 0; k<1000; k++) { System.out.println(d += doCalculatePi(k)); } gives me 3.0418396189294032 3.09162380666784 3.1082685666989476 [...] 3.1414924531892394 3.14149255348994 3.1414926535900394 ...

Why is my Spring Boot autowired JPA Repository failing JUnit test?

java,spring,junit,spring-boot

Exception comes from this line: ReflectionTestUtils.setField(userResource, "userRepository", userRepository); Second parameter of setField method is a field name. UserResource has field "repository" - not "userRepository" as you try to set in your test....

OpenJPA OneToMany and composite key in parent and child table

java,jpa,jpa-2.0,openjpa

The easiest way to do this is to create an association from ChildObj to ParentObj similar to the following: @ManyToOne(fetch = FetchType.LAZY, optional = true) @JoinColumns({ @JoinColumn(name = "serverId", referencedColumnName = "serverId"), @JoinColumn(name = "code", referencedColumnName = "code")}) private ParentObj parentObj; and then define the @OneToMany association in ParentObj like...

Creating GUI with OpenGL

java,opengl

You can check out TWL's wiki here: "http://wiki.l33tlabs.org/bin/view/TWL/" it has some basic tutorials on how to use it, and here's a "Getting Started" page for niftyGUI: https://github.com/void256/nifty-gui/wiki/Getting-Started

IllegalStateException: Iterator already obtained [duplicate]

java,file,loops,path

You have to call DirectoryStream<Path> files = Files.newDirectoryStream(dir); each time you iterate over the files. Pls check this question... java.lang.IllegalStateException: Iterator already obtained...

Get current latitude and longitude android

java,android,gps,geolocation,location

See my post at http://gabesechansoftware.com/location-tracking/. The code you're using is just broken. It should never be used. The behavior you're seeing is one of the bugs- it doesn't handle the case of getLastLocation returning null, an expected failure. It was written by someone who kind of knew what he was...

Java Scanner not reading newLine after wrong input in datatype verification while loop

java,while-loop,java.util.scanner

You are reading too much from the scanner! In this line while (sc.nextLine() == "" || sc.nextLine().isEmpty()) you are basically reading a line from the scanner, comparing it (*) with "", then forgetting it, because you read the next line again. So if the first read line really contains the...

Classes Extending Object

java

Every classes is a Sub class to Object Class. if you are extending your own class with another class. That super class is also a sub class of Object class. Suppose: Class A // extends Object { } Class B extends A { } here i am extending Class B...

Mock class inside REST controller with Mockito

java,testing,junit,spring-boot,mockito

Shouldn't you be passing an instance to set the field on, rather than the class, e.g.: ... @Autowired private Controller controller; ... @Before public void setUp() throws Exception { ... Processor processor = Mockito.mock(Processor.class); ReflectionTestUtils.setField(controller, "processor", processor); } ...

How to change the working directory of a bundled Java program

java,netbeans,bundle,executable

I'd use something like System.getenv("HOME"); to find the user's home directory instead of changing Java's working directory....

GenericApplicationContext cannot be cast to WebApplicationContext : Spring Web Flow

java,spring,spring-mvc,classcastexception,spring-webflow-2

FlowBuilderServices is meant to be a Spring-managed bean, but in your config it is just a new instance. It likes to be ApplicationContextAware and InitializingBean, but that is gonna work only if managed by Spring. The solution is simple: put @Bean on getFlowBuilderServices() method. And I think you should also...

Design suggestion: Changing the class behaviour

java,design,object-oriented-analysis

Another option is to make the action() method take an array of arguments (like main(...) does). That way ActorTwo could check the arguments to see if its in the special case, whereas the other Actors could just ignore the input. public abstract class Actor{ public abstract void action(String[] args); }...

Generic method only compiles with one argument

java,generics

The problem is that when you call addShape(someColl, new Circle()); there are two different definitions of T ? extends Shape from Collection<? extends Shape> someColl Circle from the second parameter The other problem with that call is that T needs to be a concrete type for the second parameter, i.e....

How can implement long running process in spring hibernate?

java,spring,hibernate

I recommend you to use DeferredResult of Spring. It´s a Future implementation, that use the http long poling technique. http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html So let´s says that you will make a request, and the server it will return you the deferredResult, and then your request will keep it open until the internal process(Hibernate)...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

java,android,eclipse,adt

In your MainActivity.java at line no 34 you are trying to initialize some widget that is not present in your xml layout which you have set it in your setContentView(R.layout.... That;s why you are geting nullpointerexception. EDIT: change your setContentView(R.layout.activity_main) to setContentView(R.layout.fragment_main)...

PropertyNotFoundException in jsp

java,jsp

The name of your getter & setter is wrong. By convention it must be: public Integer getSurvey_id() { return survey_id; } public void setSurvey_id(Integer survey_id) { this.survey_id=survey_id; } ...

Get element starting with letter from List

java,android,list,indexof

The indexOf method doesn't accept a regex pattern. Instead you could do a method like this: public static int indexOfPattern(List<String> list, String regex) { Pattern pattern = Pattern.compile(regex); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s != null && pattern.matcher(s).matches()) { return...

LinkedHashMap vs ArrayList with Bluetooth Scanning and ListView

java,listview,arraylist,linkedhashmap

As nobody seems to answer, I will provide my approach. 1. Duplicated entries If you like to use a List , then as I stated out in the comments, I would let your Item class override Object.equals() and Object.hashCode(). These are used internally in ArrayList.contains(). This would give you no...

Android SQLite: Fast insert/update

java,android,sqlite

What would be a correct way for overwriting existing row? Specify a conflict resolution strategy, such as INSERT OR REPLACE INTO foo ... If the insert would result in a conflict, the conflicting row(s) are first deleted and then the new row is inserted....

java Swing: how to keep one component left aligned with another component centered with respect to parent

java,swing,layout,jpanel,layout-manager

If I'm understanding your needs correctly, you want B centered relative to the parent as a whole, not centered in the space left over after A is positioned. That makes this problem interesting and after testing the other suggested answers, I don't believe they can meet that requirement. I'm having...

Why there isn't library of design patterns?

java,oop,design-patterns

Design patterns are solutions to programming problems that automatically implement good design techniques. Someone has already faced the issues you’re facing, solved them, and is willing to show you what the best techniques are. Answer to your question is - Design patterns are higher level than libraries. Design patterns tell...

setOnClickListener error Null object

java,android

After super.onCreate(savedInstanceState); insert setContentView(R.layout.YourLayout); you need to make a request to a server in another thread. It might look like public class LoginTask extends AsyncTask<Void, Void, String>{ private String username; private String password; private Context context; public LoginTask(Context context, String username, String password) { this.username = username; this.password = password;...

List view not returning to original state after clearing search

java,android,xml,android-activity,android-listfragment

You are operating on the original data instead of filtered data. You should maintain a reference to original data and use the filtered data for all other purposes. So that the original data is displayed when search is cleared. Replace all usages of mData with mFilteredData as below and only...

Bulkheading strategies for Akka actors

java,asynchronous,akka,blocking,future

If I understand this correctly, you kind of have two options here: you listen to a Future being completed or you do something with the result: If you want to listen, you can use some callback like final ExecutionContext ec = system.dispatcher(); future.onSuccess(new OnSuccess<String>() { public void onSuccess(String result) {...

App Not Downloading Newest Version Of File [Java]

java,caching,download

Use URLConnection.setUseCaches(boolean);. In your case, it would be connection.setUseCaches(false);...

Is there standard implementation for thread block/resume in java SE?

java,multithreading,wait

have a a look at the classes in java.util.conucurrent ... CountDownLatch might be a solution for your problem if i understand your problem correctly.

do calculation inside JSONArray in Java

java,arrays,json

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse: ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); JSONArray arr = new JSONArray(<JSON STRING HERE>); for(int i = 0; i < arr.length(); i ++) { JSONObject obj = arr.getJSONObject(i); JSONArray valueArray = obj.getJSONArray("values"); ArrayList<Integer> dataList...

What is the meaning of this code in Java? [on hold]

java

student2.getCourse() returns a course. It is possible to call getCourseCode() on a course. This is an example of method chaining. The equivalent code is: Course tempVar = student2.getCourse(); System.out.println("I like" + tempVar.getCourseCode()); As you learn more programming, you will find this to be consistent. A variable declared Course is clearly...