Search Results

Search found 57 results on 3 pages for 'npe'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • NullPointerException with CallableStatement.getResultSet()

    - by Raj
    Hello, I have a stored proc in SQL Server 2005, which looks like the following (simplified) CREATE PROCEDURE FOO @PARAMS AS BEGIN -- STEP 1: POPULATE tmp_table DECLARE @tmp_table TABLE (...) INSERT INTO @tmp_table SELECT * FROM BAR -- STEP 2: USE @tmp_table FOR FINAL SELECT SELECT abc, pqr FROM BAZ JOIN @tmp_table ON some_criteria END When I run this proc from SQL Server Management Studio, things work fine. However, when I call the same proc from a Java program, using something like: cs = connection.prepareCall("exec proc ?,"); cs.setParam(...); rs = cs.getResultSet(); // BOOM - Null! while(rs.next()) {...} // NPE! I fail to understand why the first result set returned is NULL. Can someone explain this to me? As a workaround, if I check cs.getMoreResults() and if true, try another getResultSet() - THIS time it returns the proper result set. Any pointers please? (I'm using JTDS drivers, if it matters) Thanks, Raj

    Read the article

  • How to demonstrate java multithreading visibility problems?

    - by Joe23
    If variables in Java are accessed from multiple threads, one must ensure that they are safely published. This usually means using synchronizedor volatile. I have got the impression, that some of my colleagues do not take this issue seriously, since they "never heard of volatile before and their programs have worked for years". So my question is: Can someone provide an example Java program/snippet, that reliably shows data visibility problems. I think running a program and seeing the unexpected NPE or stale variable value would help more, than just theoretic explanations, that cannot be demonstrated. Thanks a lot for your help!

    Read the article

  • null != null - any ideas on how to re-arrange the code or prevent this?

    - by Alex
    Currently debugging, and found an if-statement which for no (I thought...) reason gave me an NPE, obviously for a reason. Which seemed to be that the statement turned out to be if(false && (null != null || null != Color)). if(destination != null && (destination.getPiece() != null || destination.getPiece().getColour() != pieceColour)) - the if-statement Both destination can be null and piece can be. The getColour() method returns an attribute of type Color from piece, which must be null if the piece is null. The piece at destination has a different pieceColour attribute then the one in the if-statement. Specifically, how do I re-arrange (destination.getPiece() != null) ?

    Read the article

  • HTTP status code for "success with errors"?

    - by Richard Levasseur
    I've poked around a bit, but I don't see an HTTP status code for when a request's succeeds, but there is an error after the "point of no return". e.g., Say you process a request, its committed to the database, but while returning the result you run of memory, or encounter a NPE, or what have you. It would have been a 200 response, but now, internally, you aren't able to return the proper, well-formed response. 202 Accepted doesn't seem to fit since we've already processed the request. What status code means "Success, but errors"? Does one even exist?

    Read the article

  • [Android] accessing another Activity's preferences

    - by Raffaele
    I have a Login Activity which stores credentials in its own SharedPreferences; then I added two getters for reading them, something like public String getUsername() { return getPreferences(MODE_PRIVATE).getString("#username", null); } but this throws a NPE when I call it like this String mUser = (new Login()).getUsername(); It seems that the Activity cannot read its preferences after a simple contructor call, as if it were in some uncompleted state. I read lots of related topics, but wasn't able to find a solution. Basically, I need to share these credentials among activities in my application

    Read the article

  • Cascading S3 Sink Tap not being deleted with SinkMode.REPLACE

    - by Eric Charles
    We are running Cascading with a Sink Tap being configured to store in Amazon S3 and were facing some FileAlreadyExistsException (see [1]). This was only from time to time (1 time on around 100) and was not reproducable. Digging into the Cascading codem, we discovered the Hfs.deleteResource() is called (among others) by the BaseFlow.deleteSinksIfNotUpdate(). Btw, we were quite intrigued with the silent NPE (with comment "hack to get around npe thrown when fs reaches root directory"). From there, we extended the Hfs tap with our own Tap to add more action in the deleteResource() method (see [2]) with a retry mechanism calling directly the getFileSystem(conf).delete. The retry mechanism seemed to bring improvement, but we are still sometimes facing failures (see example in [3]): it sounds like HDFS returns isDeleted=true, but asking directly after if the folder exists, we receive exists=true, which should not happen. Logs also shows randomly isDeleted true or false when the flow succeeds, which sounds like the returned value is irrelevant or not to be trusted. Can anybody bring his own S3 experience with such a behavior: "folder should be deleted, but it is not"? We suspect a S3 issue, but could it also be in Cascading or HDFS? We run on Hadoop Cloudera-cdh3u5 and Cascading 2.0.1-wip-dev. [1] org.apache.hadoop.mapred.FileAlreadyExistsException: Output directory s3n://... already exists at org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:132) at com.twitter.elephantbird.mapred.output.DeprecatedOutputFormatWrapper.checkOutputSpecs(DeprecatedOutputFormatWrapper.java:75) at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:923) at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:882) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1278) at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:882) at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:856) at cascading.flow.hadoop.planner.HadoopFlowStepJob.internalNonBlockingStart(HadoopFlowStepJob.java:104) at cascading.flow.planner.FlowStepJob.blockOnJob(FlowStepJob.java:174) at cascading.flow.planner.FlowStepJob.start(FlowStepJob.java:137) at cascading.flow.planner.FlowStepJob.call(FlowStepJob.java:122) at cascading.flow.planner.FlowStepJob.call(FlowStepJob.java:42) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.j [2] @Override public boolean deleteResource(JobConf conf) throws IOException { LOGGER.info("Deleting resource {}", getIdentifier()); boolean isDeleted = super.deleteResource(conf); LOGGER.info("Hfs Sink Tap isDeleted is {} for {}", isDeleted, getIdentifier()); Path path = new Path(getIdentifier()); int retryCount = 0; int cumulativeSleepTime = 0; int sleepTime = 1000; while (getFileSystem(conf).exists(path)) { LOGGER .info( "Resource {} still exists, it should not... - I will continue to wait patiently...", getIdentifier()); try { LOGGER.info("Now I will sleep " + sleepTime / 1000 + " seconds while trying to delete {} - attempt: {}", getIdentifier(), retryCount + 1); Thread.sleep(sleepTime); cumulativeSleepTime += sleepTime; sleepTime *= 2; } catch (InterruptedException e) { e.printStackTrace(); LOGGER .error( "Interrupted while sleeping trying to delete {} with message {}...", getIdentifier(), e.getMessage()); throw new RuntimeException(e); } if (retryCount == 0) { getFileSystem(conf).delete(getPath(), true); } retryCount++; if (cumulativeSleepTime > MAXIMUM_TIME_TO_WAIT_TO_DELETE_MS) { break; } } if (getFileSystem(conf).exists(path)) { LOGGER .error( "We didn't succeed to delete the resource {}. Throwing now a runtime exception.", getIdentifier()); throw new RuntimeException( "Although we waited to delete the resource for " + getIdentifier() + ' ' + retryCount + " iterations, it still exists - This must be an issue in the underlying storage system."); } return isDeleted; } [3] INFO [pool-2-thread-15] (BaseFlow.java:1287) - [...] at least one sink is marked for delete INFO [pool-2-thread-15] (BaseFlow.java:1287) - [...] sink oldest modified date: Wed Dec 31 23:59:59 UTC 1969 INFO [pool-2-thread-15] (HiveSinkTap.java:148) - Now I will sleep 1 seconds while trying to delete s3n://... - attempt: 1 INFO [pool-2-thread-15] (HiveSinkTap.java:130) - Deleting resource s3n://... INFO [pool-2-thread-15] (HiveSinkTap.java:133) - Hfs Sink Tap isDeleted is true for s3n://... ERROR [pool-2-thread-15] (HiveSinkTap.java:175) - We didn't succeed to delete the resource s3n://... Throwing now a runtime exception. WARN [pool-2-thread-15] (Cascade.java:706) - [...] flow failed: ... java.lang.RuntimeException: Although we waited to delete the resource for s3n://... 0 iterations, it still exists - This must be an issue in the underlying storage system. at com.qubit.hive.tap.HiveSinkTap.deleteResource(HiveSinkTap.java:179) at com.qubit.hive.tap.HiveSinkTap.deleteResource(HiveSinkTap.java:40) at cascading.flow.BaseFlow.deleteSinksIfNotUpdate(BaseFlow.java:971) at cascading.flow.BaseFlow.prepare(BaseFlow.java:733) at cascading.cascade.Cascade$CascadeJob.call(Cascade.java:761) at cascading.cascade.Cascade$CascadeJob.call(Cascade.java:710) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619)

    Read the article

  • Mockito upgrade causes null pointer problems

    - by Ann Addicks
    We upgraded from mockito-all-1.8.5.jar to mockito-all-1.9.0.jar and now see null pointers when using annotations for the classes being mocked. Here is an example: @Mock private static IAccountManager accountManager; @Mock private static IBusinessUnitManager businessUnitManager; private static Gson parser; @InjectMocks private static DownloadController downloadController; @BeforeClass public static void setUpBeforeClass() throws Exception { parser = new Gson(); downloadController = new DownloadController(accountManager, businessUnitManager, parser); } @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); Mockito.reset(accountManager, businessUnitManager); } As soon as accountManager is referenced in the download controller, it throws a npe. This worked in 1.8.5.

    Read the article

  • EJB injection in Glassfish webapp

    - by g051051
    I've got an app that is trying to use @EJB annotation to inject remote references to EJBs in my ejb.jar file. I'm getting inconsistent results. In one case, I have a listener in web.xml that gets called and apparently has the EJB injected correctly, since I can see it connecting to the EJB and calling methods on it. In another class (a struts2 action) I get NPE when it tries to access the EJB reference. As far as I can tell, they're identical calls, in Java classes that live in the same .war file. As a work around, I added code in the constructor to lookup the EJBs by their global JNDI names, and it works fine. I just can't figure out why one @EJB works and not another.

    Read the article

  • Inject a EJB into a JSF converter with JEE6

    - by Michael Bavin
    Hi, I have a stateless EJB that acceses my database. I need this bean in a JSF 2 converter to retreive an entity object from the String value parameter. I'm using JEE6 with Glassfish V3 @EJB annotation does not work and gets a NPE, because it's in the faces context and it has not access to the ejb context. My question is: Is it still possible to Inject this bean (With a @Resource or other annotation, a JNDI lookup,...), or do i need a workaround? Thank you Solution Do a JNDI lookup like this: try { ic = new InitialContext(); myejb= (MyEJB) ic .lookup("java:global/xxxx/MyEJB"); } catch (NamingException e) { e.printStackTrace(); }

    Read the article

  • NullPointerException when adding to BigDecimal

    - by Dan
    String[] toppings = new String[10]; BigDecimal toppingsPrice = null; toppings[0] = req.getParameter("extraCheese"); toppings[1] = req.getParameter("moreTomatoes"); toppings[2] = req.getParameter("extraOnions"); // ... for(int i = 0; i < toppings.length; i++) { if(toppings[i] != null) { toppingsPrice.add(new BigDecimal("0.99")); // <-- NPE is caused here. toppingsPrice = toppingsPrice.setScale(2, BigDecimal.ROUND_HALF_EVEN); } } I am getting a NullPointerException in the above code when adding 0.99 to toppingsPrice. I am working with money values, so I have used BigDecimal. Is there something wrong with how I am adding the 0.99c price?

    Read the article

  • Converting SQL with subselect in select to HQL

    - by UltraVi01
    I have the following SQL that I am having problems converting to HQL. A NPE is getting thrown -- which I think has something to do with the SUM function. Also, I'd like to sort on the subselect alias -- is this possible? SQL (subselect): SELECT q.title, q.author_id, (SELECT IFNULL(SUM(IF(vote_up=true,1,-1)), 0) FROM vote WHERE question_id = q.id) AS votecount FROM question q ORDER BY votecount DESC HQL (not working) SELECT q, (SELECT COALESCE(SUM(IF(v.voteUp=true,1,-1)), 0) FROM Vote v WHERE v.question = q) AS votecount FROM Question AS q LEFT JOIN q.author u LEFT JOIN u.blockedUsers ub WHERE q.dateCreated BETWEEN :week AND :now AND u.id NOT IN ( SELECT ub.blocked FROM UserBlock AS ub WHERE ub.blocker =:loggedInUser ) AND (u.blockedUsers IS EMPTY OR ub.blocked !=:loggedInUser) ORDER BY votecount DESC

    Read the article

  • Are instance initializers good or bad?

    - by berry120
    I personally quite like instance initializers - I use them to assign default values to things such as collections so when writing constructors I don't have to remember to assign them the same default values each time. It seems quite elegant to me - avoids annoying NPE's popping up and avoids duplicate code. A private method doesn't seem as nice because a) it can't assign values to final fields, b) it could be run elsewhere in code and c) the method still needs to be explicitly called at the start of each constructor. However, the flip side with others I have spoken to is that they're confusing, some people reading the code might not understand what they do or when they're called and thus they could cause more problems than they solve. Are proper use of these initializers something to be encouraged or avoided? Or is it an "each to their own" case?

    Read the article

  • As the current draft stands, what is the most significant change the "National Strategy for Trusted Identities in Cyberspace" will provoke?

    - by mfg
    A current draft of the "National Strategy for Trusted Identities in Cyberspace" has been posted by the Department of Homeland Security. This question is not asking about privacy or constitutionality, but about how this act will impact developers' business models and development strategies. When the post was made I was reminded of Jeff's November blog post regarding an internet driver's license. Whether that is a perfect model or not, both approaches are attempting to handle a shared problem (of both developers and end users): How do we establish an online identity? The question I ask here is, with respect to the various burdens that would be imposed on developers and users, what are some of the major, foreseeable implementation issues that will arise from the current U.S. Government's proposed solution? For a quick primer on the setup, jump to page 12 for infrastructure components, here are two stand-outs: An Identity Provider (IDP) is responsible for the processes associated with enrolling a subject, and establishing and maintaining the digital identity associated with an individual or NPE. These processes include identity vetting and proofing, as well as revocation, suspension, and recovery of the digital identity. The IDP is responsible for issuing a credential, the information object or device used during a transaction to provide evidence of the subject’s identity; it may also provide linkage to authority, roles, rights, privileges, and other attributes. The credential can be stored on an identity medium, which is a device or object (physical or virtual) used for storing one or more credentials, claims, or attributes related to a subject. Identity media are widely available in many formats, such as smart cards, security chips embedded in PCs, cell phones, software based certificates, and USB devices. Selection of the appropriate credential is implementation specific and dependent on the risk tolerance of the participating entities. Here are the first considered actionable components of the draft: Action 1: Designate a Federal Agency to Lead the Public/Private Sector Efforts Associated with Achieving the Goals of the Strategy Action 2: Develop a Shared, Comprehensive Public/Private Sector Implementation Plan Action 3:Accelerate the Expansion of Federal Services, Pilots, and Policies that Align with the Identity Ecosystem Action 4:Work Among the Public/Private Sectors to Implement Enhanced Privacy Protections Action 5:Coordinate the Development and Refinement of Risk Models and Interoperability Standards Action 6: Address the Liability Concerns of Service Providers and Individuals Action 7: Perform Outreach and Awareness Across all Stakeholders Action 8: Continue Collaborating in International Efforts Action 9: Identify Other Means to Drive Adoption of the Identity Ecosystem across the Nation

    Read the article

  • Reverse and Forward DNS set up correctly but sometimes MapReduce job fails

    - by phodamentals
    Ever since we switched over our cluster to communicate via private interfaces and created a DNS server with correct forward and reverse lookup zones, we get this message before the M/R job runs: ERROR org.apache.hadoop.hbase.mapreduce.TableInputFormatBase - Cannot resolve the host name for /192.168.3.9 because of javax.naming.NameNotFoundException: DNS name not found [response code 3]; remaining name '9.3.168.192.in-addr.arpa' A dig and nslookup both show that the reverse and forward look-ups both get good responses with no errors from within the cluster. Shortly after these messages, the job runs...but every once in awhile we get a NPE: Exception in thread "main" java.lang.NullPointerException INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.net.DNS.reverseDns(DNS.java:93) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.reverseDNS(TableInputFormatBase.java:219) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.getSplits(TableInputFormatBase.java:184) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapred.JobClient.writeNewSplits(JobClient.java:1063) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapred.JobClient.writeSplits(JobClient.java:1080) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapred.JobClient.access$600(JobClient.java:174) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:992) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:945) INFO app.insights.search.SearchIndexUpdater - at java.security.AccessController.doPrivileged(Native Method) INFO app.insights.search.SearchIndexUpdater - at javax.security.auth.Subject.doAs(Subject.java:415) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1408) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:945) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapreduce.Job.submit(Job.java:566) INFO app.insights.search.SearchIndexUpdater - at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:596) INFO app.insights.search.SearchIndexUpdater - at app.insights.search.correlator.comments.CommentCorrelator.main(CommentCorrelator.java:72 Does anyone else who has set-up a CDH Hadoop cluster on a private network w/DNS server get this? CDH 4.3.1 with MR1 2.0.0 and HBase 0.94.6

    Read the article

  • Programmatically creating scrollview(s) from custom component in android

    - by jaapbeetstra
    I'm trying to build a compound control in Android, containing (among other things) a ScrollView. Things go wrong when I try to view the control in Eclipse, crashing with a NullPointerException after the error message: "Parser is not a BridgeXmlBlockParser". Stacktrace: java.lang.NullPointerException at android.view.View.<init>(View.java:1720) at android.view.ViewGroup.<init>(ViewGroup.java:277) at android.widget.FrameLayout.<init>(FrameLayout.java:83) at android.widget.ScrollView.<init>(ScrollView.java:128) at android.widget.ScrollView.<init>(ScrollView.java:124) at android.widget.ScrollView.<init>(ScrollView.java:120) at my.compound.control.StringPicker.onMeasure(StringPicker.java:46) ... I've traced the error to the following conditions: The NPE is thrown because a Context.obtainStyledAttributes() call returns null when the attrs argument passed is null. This only applies to the BridgeContext implementation used in Eclipse, which expects attrs to be an instance of the BridgeXmlBlockParser. The attrs argument is null because I create the ScrollView using the (Context) constructor. There is a workaround of course, which is passing the attrs I receive when Eclipse constructs the compound control, but I don't want all the attributes set on the compound control to apply to my inner control. Am I doing something wrong, is this a bug in Android Eclipse, ...?

    Read the article

  • How do I get folder size with Exchange Web Services 2010 Managed API?

    - by Adam Tuttle
    I'm attempting to use EWS 2010 Managed API to get the total size of a user's mailbox. I haven't found a web service method to get this data, so I figured I would try to calculate it. I found one seemingly-applicable question on another site about finding mailbox sizes with EWS 2007, but either I'm not understanding what it's asking me to do, or that method just doesn't work with EWS 2010. Noodling around in the code insight, I was able to write what I thought was a method that would traverse the folder structure recursively and result in a combined total for all folders inside the Inbox: private int traverseChildFoldersForSize(Folder f) { int folderSizeSum = 0; if (f.ChildFolderCount > 0) { foreach (Folder c in f.FindFolders(new FolderView(10000))) { folderSizeSum += traverseChildFoldersForSize(c); } } folderSizeSum += (int)f.ManagedFolderInformation.FolderSize; return folderSizeSum; } (Assumes there aren't more than 10,000 folders inside a given folder. Figure that's a safe bet...) Unfortunately, this doesn't work. I'm initiating the recursion with this code: Folder root = Folder.Bind(svc, WellKnownFolderName.Inbox); int totalSize = traverseChildFoldersForSize(root); But a Null Pointer Exception is thrown, essentially saying that [folder].ManagedFolderInformation is a null object reference. For clarity, I also attempted to just get the size of the root folder: Console.Write(root.ManagedFolderInformation.FolderSize.ToString()); Which threw the same NPE exception, so I know that it's not just that once you get to a certain depth in the directory tree that ManagedFolderInformation doesn't exist. Any ideas on how to get the total size of the user's mailbox? Am I barking up the wrong tree?

    Read the article

  • Java conditional operator ?: result type

    - by Wangnick
    I'm a bit puzzled about the conditional operator. Consider the following two lines: Float f1 = false? 1.0f: null; Float f2 = false? 1.0f: false? 1.0f: null; Why does f1 become null and the second statement throws a NullPointerException? Langspec-3.0 para 15.25 sais: Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7). So for false?1.0f:null T1 is Float and T2 is the null type. But what is the result of lub(T1,T2)? This para 15.12.2.7 is just a bit too much ... BTW, I'm using 1.6.0_18 on Windows. PS: I know that Float f2 = false? (Float) 1.0f: false? (Float) 1.0f: null; doesn't throw NPE.

    Read the article

  • How to get the stacktrace in a mobile device?

    - by Daniel Moura
    I'm getting a NullPointerException in a Nokia S40. I want to know what is causing this exception. The device shows: NullPointerException java/lang/NullPointerException This error only occurs in the device, running in the emulator the application works fine. I use microlog to debug my application. But the application works fine if the log is enabled. Is there a way to get the stack trace when I get this NullPointerException? I don't need all details like the line number just which method cause this exception. UPDATE: I installed the same application in another Nokia S40 and the same error didn't occur. Nokia 2660 - error Nokia 6131 - no error UPDATE 2: Somehow I find what was causing the NullPointerException. import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Graphics; public class OuterClass extends Canvas { private Config config; public OuterClass() { this.config = new Config(); } public void paint(Graphics graphics) { HelperClass helper = new HelperClass(this.config); helper.doStuff(); } public void dispose() { this.config = null; } public class Config implements IConfig { public int getSomething() { // ... } } } public class HelperClass { private IConfig config; public HelperClass(IConfig) { this.config = config; } public doStuff() { config.getSomething(); // Here is thrown NullPointerException } } In some situations a thread is started and call the OuterClass.dispose() before the helper.doStuff() causing the NPE. I think when I enabled the log it made the thread slower and helper.doStuff() was called when I expected it to be called.

    Read the article

  • How to ask BeanUtils to ignore null values

    - by Calm Storm
    Using Commons beanUtils I would like to know how to ask any converter say the Dateconverter to ignore null values and use null as default. As an example consider a public class, public class X { private Date date1; private String string1; //add public getters and setters } and my convertertest as, public class Apache { @Test public void testSimple() throws Exception { X x1 = new X(), x2 = new X(); x1.setString1("X"); x1.setDate1(null); org.apache.commons.beanutils.BeanUtils.copyProperties(x2, x1); //throws ConversionException System.out.println(x2.getString1()); System.out.println(x2.getDate1()); } } The above throws a NPE since the date happens to be null. This looks a very primitive scenario to me which should be handled by default (as in, I would expect x2 to have null value for date1). The doco tells me that I can ask the converter to do this. Can someone point me as to the best way for doing this ? I dont want to get hold of the Converter and isUseDefault() to be true because then I have to do it for all Date, Enum and many other converters !

    Read the article

  • Removing PDF attachments via itext

    - by r00fus
    I'm trying to remove attachments from a number of my pdf files (I can extract via pdftk, so preserving them is not an issue). I coded the following based on an example found from a google search: import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.*; import com.lowagie.text.pdf.*; class pdfremoveattachment { public static void main(String[] args) throws IOException, DocumentException { if (args.length < 2) { System.out.println("Usage: java PDFremoveAttachments source.pdf target.pdf"); System.exit(1); } PdfReader sourcePDF = new PdfReader(args[0]); removeAttachments(sourcePDF); FileOutputStream targetFOS = new FileOutputStream(args[1]); PdfStamper targetPDF = new PdfStamper(sourcePDF,targetFOS); targetPDF.close(); } public static void removeAttachments(PdfReader reader) { PdfDictionary catalog = reader.getCatalog(); // System.out.println(catalog.getAsDict(PdfName.NAME)); // this would print "null" PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.NAMES)); // System.out.println(names.toString()); //this returns NPE if( names != null) { PdfDictionary files = (PdfDictionary) PdfReader.getPdfObject(names.get(PdfName.FILEATTACHMENT)); if( files!= null ){ for( Object key : files.getKeys() ){ files.remove((PdfName)key); } files = (PdfDictionary) PdfReader.getPdfObject(names.get(PdfName.EMBEDDEDFILES)); } if( files!= null ){ for( Object key : files.getKeys() ){ files.remove((PdfName)key); } reader.removeUnusedObjects(); } } } } If anyone knows how I might be able to remove attachments, I'd greatly appreciate a reply.

    Read the article

  • Apache CXF REST Services w/ Spring AOP

    - by jconlin
    I'm trying to get Apache CXF JAX-RS services working with Spring AOP. I've created a simple logging class: public class AOPLogger{ public void logBefore(){ System.out.println("Logging Before!"); } } My Spring configuration (beans.xml): <aop:config> <aop:aspect id="aopLogger" ref="test.aop.AOPLogger"> <aop:before method="logBefore" pointcut="execution(* test.rest.RestService(..))"/> </aop:aspect> </aop:config> <bean id="aopLogger" class="test.aop.AOPLogger"/> I always get an NPE in RestService when a call is made to a Method getServletRequest(), which has: return messageContext.getHttpServletRequest(); If I remove the aop configuration or comment it out from my beans.xml, everything works fine. All of my actual Rest services extend test.rest.RestService (which is a class) and call getServletRequest(). I'm just trying to just get AOP up and running based off of the example in the CXF JAX-RS documentation. Does anyone have any idea what I'm doing wrong? Thanks!

    Read the article

  • Why does autoboxing in Java allow me to have 3 possible values for a boolean?

    - by John
    Reference: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html If your program tries to autounbox null, it will throw a NullPointerException. javac will give you a compile-time error if you try to assign null to a boolean. makes sense. assigning null to a Boolean is a-ok though. also makes sense, i guess. but let's think about the fact that you'll get a NPE when trying to autounbox null. what this means is that you can't safely perform boolean operations on Booleans without null-checking or exception handling. same goes for doing math operations on an Integer. for a long time, i was a fan of autoboxing in java1.5+ because I thought it got java closer to be truly object-oriented. but, after running into this problem last night, i gotta say that i think this sucks. the compiler giving me an error when I'm trying to do stuff with an uninitialized primitive is a good thing. I think I may be misunderstanding the point of autoboxing, but at the same time I will never accept that a boolean should be able to have 3 values. can anyone explain this? what am i not getting?

    Read the article

  • Remove Empty Attributes from XML

    - by er4z0r
    Hi, I have a buggy xml that contains empty attributes and I have a parser that coughs on empty attributes. I have no control over the generation of the xml nor over the parser that coughs on empty attrs. So what I want to do is a pre-processing step that simply removes all empty attributes. I have managed to find the empty attribus, but now I don't know how to remove them: XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); XPathExpression expr = xpath.compile("//@*"); Object result = expr.evaluate(d, XPathConstants.NODESET); if (result != null) { NodeList nodes = (NodeList) result; for(int node=0;node<nodes.getLength();node++) { Node n = nodes.item(node); if(isEmpty(n.getTextContent())) { this.log.warn("Found empty attribute declaration "+n.toString()); NamedNodeMap parentAttrs = n.getParentNode().getAttributes(); parentAttrs.removeNamedItem(n.getNodeName()); } } } This code gives me a NPE when accessing n.getParentNode().getAttributes(). But how can I remove the empty attribute from an element, when I cannot access the element?

    Read the article

  • Java Concurrency in practice sample question

    - by andy boot
    I am reading "Java Concurrency in practice" and looking at the example code on page 51. This states that if a thread has references to a shared object then other threads may be able to access that object before the constructor has finished executing. I have tried to put this into practice and so I wrote this code thinking that if I ran it enough times a RuntimeException("World is f*cked") would occur. But it isn't doing. Is this a case of the Java spec not guaranting something but my particular implementation of java guaranteeing it for me? (java version: 1.5.0 on Ubuntu) Or have I misread something in the book? Code: (I expect an exception but it is never thrown) public class Threads { private Widgit w; public static void main(String[] s) throws Exception { while(true){ Threads t = new Threads(); t.runThreads(); } } private void runThreads() throws Exception{ new Checker().start(); w = new Widgit((int)(Math.random() * 100) + 1); } private class Checker extends Thread{ private static final int LOOP_TIMES = 1000; public void run() { int count = 0; for(int i = 0; i < LOOP_TIMES; i++){ try { w.checkMe(); count++; } catch(NullPointerException npe){ //ignore } } System.out.println("checked: "+count+" times out of "+LOOP_TIMES); } } private static class Widgit{ private int n; private int n2; Widgit(int n) throws InterruptedException{ this.n = n; Thread.sleep(2); this.n2 = n; } void checkMe(){ if (n != n2) { throw new RuntimeException("World is f*cked"); } } } }

    Read the article

  • How to enforce jsf to create new instance of bean instead of throwing NullPointerException?

    - by Roman
    I'm almost sure that I do something wrong and thus the question's title is a bit incorrect. I have a form with several fields for creating a new User-objects (fields like login, password, birthday etc). And I have 2 buttons - Cancel and Create. I didn't finish Create yet :) , but when I press Cancel I see NullPointerException. Here is simplified code: <f:view> <h:form> <h:panelGroup layout="block"> <h:inputText id="add_login" value="#{userSupport.user.login}"/> <h:inputSecret id="add_password" value="#{userSupport.user.password}"/> <h:inputText id="add_name" value="#{userSupport.user.name}"/> <h:inputText id="add_surname" value="#{userSupport.user.surname}"/> <h:commandButton value="Cancel" action="cancel"/> </h:panelGroup> </h:form> </f:view> UserSupport class has field user with getter and setter and some other methods. It's a Spring bean with Session scope. When I press cancel, I see NPE because jsf tries to save values from inputs in user-object, but user-object is null. What is the correct way of doing this?

    Read the article

< Previous Page | 1 2 3  | Next Page >