Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
geeves
Sep 16, 2004

This is more an Eclipse setup question (and I come from an IntelliJ setup so Eclipse is very new to me)

Project tree is /svn/project/trunk/core/src/main/java/com/company/package/class

Project builds fine with Maven, and works properly when deployed; however Eclipse keeps throwing errors that: com.company.package is not valid and needs to be main.java.com.package.

It also does not recognize / reference other classes within the same package. Eclipse can see my Maven repo, but not this. :wtc:

I have the same project setup with IntelliJ and it's working fine.

Using Dynamic Web Project at the moment, but the others had similar results. Is this a setting or in the type of project it should be?

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

zootm posted:

Are you using the Maven plugin for Eclipse? I imagine some horrors occur trying to make Maven's ultra-consistent weirdness work within an ad-hoc project context.

I have m2eclipse installed, but I don't think I'll use, I usually just build from the command line. I had the MVN plugin for IntelliJ installed and maybe used it once total over 3 years.

quote:

This sounds like Eclipse doesn't know what your root source directory is . In the project properties, set the source directory to that "main/java". Then the packages will follow from there( eclipse will properly see com.company.package as the package).

Yep, this was it - thanks!

geeves
Sep 16, 2004

This isn't exactly elegant or the best solution.

I have 1000s of XML files that reference each other. Each xml file has a "story_id" and may contain a "related_story_id".

The related_story_id matches the file's name story_[related_story_id].xml

Then it reads the related file and adds the primary_uri element value to a String[].

This is all output of Bricolage (an archaic and terrible CMS) via SOAP; unfortunately there's no time to go through and traverse the DB schema, but after spending the past few hours on this, I'm starting to wonder if it would be quicker.

in "parseRelatedStory" I'm getting a NullPointerException and no values are being added to String[] relatedLinks and the line after which should output to the log file does not work.

Should String[] relatedLinks actually be a HashMap? This nearly same block of code (except for a different subset of elements in the same XML file) works. I'm not sure why it may be failing here.


code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assets xmlns="http://bricolage.sourceforge.net/assets.xsd">
 <story id="37903" uuid="387EB6AC-3BCA-11DE-97D9-53C038788F35" element_type="product_page">
  <primary_uri>/pubs/corporate_pubs/CP558/index.html</primary_uri>
  <elements>
   <container order="15" element_type="linkbar">
    <container order="0" element_type="bricolage_link" related_story_id="37485">
     <field order="0" type="link_text">Catalog</field>
    </container>
    <container order="1" element_type="bricolage_link" related_story_id="37482">
     <field order="0" type="link_text">Brochure</field>
    </container>
    <container order="2" element_type="bricolage_link" related_story_id="37483">
     <field order="0" type="link_text">Brochure</field>
    </container>
    <container order="3" element_type="bricolage_link" related_story_id="37484">
     <field order="0" type="link_text">East Brochure</field>
    </container>
   </container>
  </elements>
 </story>
</assets>
php:
<?

private String[] relatedLinks;

public String[] execute() {

    Iterator<Element> childs = null;
    Element child = null;

// field is private, but set here by a setter
    childs = field.getChildren().iterator();
    while (childs.hasNext()) {
        child = (Element) childs.next();
        if ("linkbar".equals(kid.getAttributeValue("element_type"))) {
            parseStoryXml(child);
        }
    }
    return relatedLinks;
}

private void parseStoryXml(Element elements) {

    Iterator<Element> containers = elements.getChildren().iterator();
    Element container = null;
    int i = 0;
    while (containers.hasNext()) {
        container = (Element) containers.next();
        if ("bricolage_link".equals(container.getAttributeValue("element_type"))) {
            if (!"".equals(container.getAttributeValue("related_story_id"))) {
                String story_id = "story_" + container.getAttributeValue("related_story_id");
                parseRelatedStory(story_id, i);
                i++;
            }

        } else if ("non_cms_link".equals(container.getAttributeValue(element_type))) {
            parseExternalLink(container, i);
            i++;
        }
    }
}

private void parseRelatedStory(String story_id, int i) {

    try {
        Document doc = null;
        String fileName = getRelatedUri(story_id);
        boolean isPrimaryUri = false;
  
            SAXBuilder sax = new SAXBuilder();
            doc = sax.build(fileName);

            Element assets = doc.getRootElement();
            Element story = null;
            Element field = null;

            Iterator<Element> fields = null;
            Iterator<Element> stories = assets.getChildren().iterator();

            while (stories.hasNext()) {

                story = (Element) stories.next();
                fields = story.getChildren().iterator();

                while (fields.hasNext()) {
                    field = (Element) fields.next();
                    if ("primary_uri".equalsIgnoreCase(field.getName())) {
                        if (!"".equals(field.getValue())) {
                            isPrimaryUri = true;
                            log.info("main story: " + storyId);
                            log.info("FileName: " + fileName);
                            log.info("Primary URI: " + i + " : " + field.getValue());
                            
                            // All of these logs show up when the script is running.
                            // nothiing is added to relatedLinks
                            relatedLinks[i] = field.getValue();

// this does not output to the error.log file!
                            log.info("relatedLinks length: " + relatedLinks.length);
                        }
                        // no need to continue parsing the XML file
                        break;
                    }
                }
                if (isPrimaryUri) {
                // no need to continue parsing the XML file
                    break;
                }
            
        } else {
            log.error("fileName is NULL");
        }
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        log.error("parseRelatedStory:JDOM: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("parseRelatedStory:IOException - Most likely FileNotFound " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) { // also tried this with NullPointerException  - catch works, no message
    // e.getMessage doesn't show anything
        log.error("parseRelatedStory:Exception " + story_id + " " + e.getMessage());
    }
}

?>
^^ I also tried to specifically use NullPointerException - also worked, but no additional info.


Log file output this repeats for each main story_id
code:
*INFO* GET /pubsImport.html ] BricXMLParseHelper main story: 37899
*INFO* GET  /pubsImport.html ] BricXMLParseHelper FileName: /dev1/product_page_xml/story_37939.xml
*INFO* GET  /pubsImport.html ] BricXMLParseHelper Primary URI: 0 : /CP562.1/index.html
*ERROR* GET  /pubsImport.html ]BricXMLParseHelper parseRelatedStory:Exception story_37939

Any thoughts? Am I blatantly missing something?

geeves
Sep 16, 2004

tkinnun0 posted:

I don't see relatedLinks being initialized, so it's probably null. Another thing is that arrays in Java do not expand after creation.

Taken together, relatedLinks should be

List<String> relatedLinks = new ArrayList<String>();

Thanks!

That took care of it. I've been switching between Java, JavaScript, Sling and PHP too much the past few days and I've pretty much just been cross-eyed because of it.

geeves
Sep 16, 2004

Parantumaton posted:

Maven, however, doesn't improve your build quality at all, it's like sticking ice picks into your eyes. You're better off making reusable Ant scripts and using Ivy for dependency management.

Everyone seems to be torn (well not torn on opposite ends) on this , myself included. My old job moved from custom Ant scripts to Maven. Never really noticed any major issues except that we had several POMs per project and if one was out of sync, build would fail. Over all I like Maven and I like that Maven is pretty simple to setup and use from the start, but some things still trip me up and online help / documentation doesn't seem to cover it.

My main issue with Maven: it's either all or nothing with including dependencies. I can't just add what's needed. This is especially frustrating since I work with OSGI and it's easier to include dependent jars in the build jar instead of going through the hassle of Bundle-ing them or hacking them to pieces ( had to do this with Apache POI) but that's another thread.

geeves fucked around with this message at 06:15 on Nov 19, 2009

geeves
Sep 16, 2004

Actually, based on my last post I have a question:

Is it bad form to hack apart and repackage Jar files, especially those from Maven repos?

I work with OSGI, so it's a bit of a pain and here's why:

We need Apache POI for dealing with Excel documents (we dont' need POI, but it's super easy to work with and we're only reading before passing data onto the JCR).

But when loading into OSGI we need 2 jars: poi-3.x-FINAL and poi-ooxml-3.x-FINAL

Basically to instantiate the code it's:

Workbook wb = WorkbookFactory.create(InputStream in);

Well, WorkbookFactory is in poi-ooxml and Workbook is in poi-3.x yet they're in the same location / package (org.apache.poi.ss.usermodel)

OSGI will only load the classes of the package of the jar that's loaded first. So if I load poi-3.x first WorkbookFactory is not seen (even if it's in the MANIFEST) or if I load poi-ooxml first, Workbook (and other classes in poi-3.x) won't be seen or available.

I get this as a fail-safe.

To get POI to work, I had to extract the jars, move WorkbookFactory into poi instead of poi-ooxml (it was the only class in that package in poi-ooxml) then re-jar the classes, create bundles using Bnd (http://www.aqute.biz/Code/Bnd) and upload them to my OSGI manager.

It works. I couldn't be happier.

But, is this retarded or stupid? Is there a better way? Related to the above issue that, for me, Maven has been an all or nothing build with my dependencies (many of which are already loaded into the OSGI repo that I'm using). Hence why I had to find an alternative to include 3rd-party packages.

On the final note: I really like OSGI - it's saved lots of time in restarting the webserver as well as giving an immediate rundown on what's working or what's not because of a dependcy missing. But some things are a bit of a pain that could be solved in other stages of development.

geeves
Sep 16, 2004

I'm having a problem setting a cookie via the HttpServletResponse object with all flavors of IE. When in debug mode, everything is set as it should be and I can follow the Response through the Servlet and the JSP code. But it fails to be set.

Is there something I'm missing with IE? I have never run into this problem with JavaScript or PHP or even Java before. Firefox, Opera, Safari, Chrome all work as expected. It's just IE.

In a method for UserLogin I have the following:

php:
<?

Cookie fooCookie = Bar.addCookeu(handler, request);
if(null != fooCookie) {
  reponse.addCookie(fooCookie);
}

.....

// in Class Bar:
public static Cookie addCookie(ContactHandler handler, HttpServletRequest request) {
        Cookie fooCookie = null;
        String uuid = "";
        String pass = "";
        int age = -1000;
        String cookieString = null;
        
        if(null != handler) {
            uuid = handler.getUuid();
            pass = handler.getPassword();
            age = (handler.isRememberMe()) ? Constants.COOKIE_LENGTH_REMEMBER : Constants.COOKIE_LENGTH_DEFAULT;
            cookieString = uuid + ";" + pass;
            log.info("Cookie String: " + cookieString);
        }
        try {
            fooCookie = new Cookie(Constants.COOKIE, cookieString);
            String serverName = ".foo.org";
            
            fooCookie.setDomain(serverName);
            
            fooCookie.setPath("/");
            fooCookie.setMaxAge(age);
           
        } catch (Exception e) {
            log.error("CAN'T ADD COOKIE: " + e.getMessage());
        }
        return fooCookie;

    }
?>

geeves
Sep 16, 2004

dreamality posted:

I believe it's got something to do with
code:
String serverName = ".foo.org";
fooCookie.setDomain(serverName);
remove the domain or place a correct domain, if running on localhost, might want to try localhost.

If that still doesn't work try removing all other "sets" and do a simple cookie:
code:
fooCookie = new Cookie("name","value");
see if that works, at least that will point you to the right direction.

Good Luck

foo.org is just replacing my company's domain.)

I'll try a simpler one and it fails with and without setDomain().

geeves
Sep 16, 2004

tef posted:

Any recommended json libraries or such?

I've been looking at this as well and currently have been comparing json.org/java vs json-lib.sourceforge.net (based on json.org but probably a bit more developed, according to them) and Jackson http://jackson.codehaus.org/

There is also one in Sling, but it's a bit limited and geared toward working with a JCR.

geeves
Sep 16, 2004

I have a question about performance and loops. Right now it works, but I'm looking for efficiency.

I guess this is more general programming than Java, but here it goes.

I am getting a list of tags, looping through them and then looping through the list of pages each of them return. I'm working with a Java Content Repository. So I have a loop within a loop. I've never thought this was ideal.

I'm still a somewhat Java beginner when it comes to certain concepts, but I hate nested IF statements, especially when checking for NULL. Should I leave that to the catch / exception handling? If something is null I don't want it to kill the whole loop, just ignore it (and log it, of course).

Should the second loop be another method or does that not matter? Is it better to have a nested try/catch/ finally? Should these be in a separate method? Is it personal preference? Or just something I'm stuck with?

Besides working, I like to go for readability and I know I'm not perfect in that area, but I do try my best.

code:
Iterator<Entry<String, Integer>> it = tagMapFromContent.entrySet().iterator();

HashMap<String, Integer> contentWeight = new HashMap<String, Integer>();

try {
    tagLoop: while (it.hasNext()) {
        Entry<String, Integer> e = it.next();
        Tag tag = getTagFromPath(e.getKey(), resourceResolver);

        if (null != tag) {

        pageLoop: while (res.hasNext()) {
                    Integer weight = tagMapFromContent.get(tag.getPath());
                    Resource r = res.next();
                    // Node n = r.adaptTo(Node.class);
                    String path = r.adaptTo(Node.class).getParent().getPath();
                    Page page = resourceResolver.getResource(path).adaptTo(Page.class);
                    if (null != page) {
                      //more logic
                    }
         }
    }

} catch(Exception e) {
  //handle exception
}

geeves
Sep 16, 2004

HFX posted:

I'm having a bit of trouble figuring out the bigger picture of what you are doing (which could help me recommend something better for you).


A simple weighting system for recommending an item for a user.

I have, for example, 7 tags on an Item. Each of those tags maybe used on 40 or 50 other Items. If an item already exists in the HashMap, then its weight (the Integer) is added. If it's a certain "mega" Item, its weight is +2 instead of +1. That's a simple if/else in the if (null != page)

quote:


So I'll talk you a bit about what I do get.


First efficiency is something to be careful about. How often is this running as part of your whole program? Are you spending an inordinate amount of time in it and why?

It runs only when a user saves an item to their cart. I don't know how often this will run. We know very little of the behavior of our visitors aside from what basic HTTP stats will tell us. Our site however gets upwards of 600-700k unique visits per month and 4-5 million page views per month. How many people will register and save content - I don't know. Nobody does and yes, that is the problem.

This is an entirely new feature and we're going from a completely static HTML site (managed with a "baked" CMS) to a JCR-based content repository. Basically I'm thinking worst case scenario.

quote:

Now for your code:
The loops themselves would probably be better labeled using a comment or even better your method has a descriptive name minimizing the need for a comment. The inner loop is a good target for a private method. Java doesn't support private methods for a given method, so you will have to put it in the class itself. The outer loop could be also, but I can't see your whole method.


That is the whole method, minus an if/else statement in the inner loop. I used to write a lot of loops for some hosed up business logic that needed to break the outer loop, so it's an old habit to label them in that way.

quote:


Do not worry about checking for nulls. This is actually how you want to write your code if you expect nulls. Avoid throwing exceptions except in exceptional circumstances.

That's been the problem with development, we have so much content and items that it's several gigs to import onto our local machines. That and there were several iterations of importing (to find the best structure in the JCR) so it was just easier to check for null or else it would throw a NullPointer and kill action.

quote:

With more knowledge about what you are trying to achieve, I possibly could recommend a better way of solving it, however, there is nothing super wrong about code.

geeves
Sep 16, 2004

Not a specific code question

When are the best times to synchronize? It seems like the logical choice is for when transactions occur (adding / modifying database or repository).

But are there other times when synchronization becomes crucial? Or should it be kept to the minimum?

geeves
Sep 16, 2004

wigga please posted:

I'm a .NET guy, pretty new to Java, and iI have a Struts/EJB question. I'm trying to teach myself some stuff but I'm pretty disappointed in the tutorials I found so far.

I have two separate problems:the first, is just getting data from a simple query to display. I have a GetMessagesAction that exposes a "messages" property. I've tried to make this a ResultSet (although if resultset is anything like and ADO.NET DataSet I probably shouldn't use that), a HashMap, and just concatenating everything into a string (which is probably the worst but at least it displays anything).
How should I configure my JSP page to display this? <bean:write .../> cuts it for strings, but not for Collections or ResultSets (blank).
I tried <logic:iterate.../> but that just gets me a 500 error "No collection found". So I'm actually looking to find something comparable to the ASP.NET GridView or ListView controls.

Next, is a system that allows a user to submit a message once he has identified himself. The problem here is that I can get the username from a bean, but I wouldn't know how to pass it to the messaging bean. Load it into session? Get it from one of the form properties in the MessagesAction model?


Any collection should do.. have you tried using <logic:present> to see if it's been loaded / available? Are you able to access the Collection with JSP instead of struts tags? Also, just a quick check - you are including the logic taglib, right? That last one has lead me to many headaches over time.

http://struts.apache.org/1.2.9/userGuide/struts-logic.html#iterate


As for the second, yes, at my old job we loaded everything into the session scope on success of the Action.

geeves
Sep 16, 2004

Does anyone have any recommendations for a solid and free / inexpensive code profiler? Perhaps one that's a plugin for eclipse?

geeves
Sep 16, 2004

crazyfish posted:

My personal favorite profiler that I use is jProfiler, however whether or not it will work for you depends on your definition of inexpensive. An academic license is $200 and a full license is $500.

Thanks,

We're a non-profit, and might be able to qualify for an academic license.

I've never been the one to set up the profiler before and with only 2 other developers most is falling on my shoulders since the they are pretty much new to Java and my boss is paranoid about performance and potential memory leaks coming from a C/C++ background.

geeves
Sep 16, 2004

I'm building a search based on weightings of Tags that ends with returning Weighted HTML pages. For example Tag A would have a value of 5, Tag B: 3, Tag C: 2, Tag D: 1.

These are used as search parameters for a Lucene search with XPath. This search is ridiculously fast. It's searching through about 80,000 pages. Takes less than a second most searches.

Search returns Page A that has Tags B & C, Page B has tags A, C & D and so on.

Anyway, that's not the problem, the search on average returns 6500-8000 Pages. Each Page has a certain number of Tags assigned to it, so now I have a loop in a loop.

I have to go in and weight the returned Pages and order them descending. I'm using a HashMap<String, Integer> (Page.getPath(), Total Weight) right now to handle this, but I don't this this is the best way and this adding of total weights.

So I end up with something like this. Not pretty, but I'm at a loss on how to improve this or if I should even be using a Map for this (I inherited the initial version from a Contractor we had and all around his code was sub-par) . Right now this part takes ~6 seconds to run.

code:
HashMap<String, Integer> tagWeights = getTagWeights();
HashMap<String, Integer> pageWeights = new HashMap<String, Integer>();

PageIterator<Page> pi = executeSearch(query);

while(pi.hasNext()) {
  
  Page p = pi.next();
  Tag[] tag = p.getTags();

  for (int i = 0; i < tag.length; i++) {
    if (tagWeights.containsKey(tags[i].getName())) {

      Integer weight = tagWeights.get(tags[i].getName());
      if (pageWeights.containsKey(page.getPath())) {
        Integer tmp = allContentAndWeights.get(page.getPath());
        pageWeights.put(page.getPath(), tmp + weight);
      } else {
        pageWeights.put(page.getPath(), weight);
      }

    }
  }
}

geeves
Sep 16, 2004

TRex EaterofCars, Added the initial capacity, didn't make much difference.

rjmccall posted:

1. Consider whether you can reasonably just add this as an int field to Page.

Page is actually a Node (we're using a JCR) and it's its own object. I even went as far as thinking to extend it for this purpose, but that might be overkill.

quote:

2. You're doing a lot of unnecessary re-lookups. This actually hashes the tag name twice:
code:
if (tagWeights.containsKey(tags[i].getName())) {
  Integer weight = tagWeights.get(tags[i].getName());
Just call get() and check the result for null. Similarly with your pageWeights lookup.

Did this, no improvement.

quote:

3. Profile.
Working on this bit. There's only 2 of us doing a gargantuan amount of work (most of my work has been fixing most of what this contractor did for us. This is the last bit I'm trying to fix. I had a few suggestions earlier in this thread, but haven't had time to really explore them other than downloading what is necessary and read some "Getting Started" material.

quote:

4. If Page is hashed/compared by object identity, consider using an IdentityHashMap. It's actually a totally different hash implementation from HashMap which is (1) substantially faster and (2) substantially less memory hungry.

This is where I am now. Giving it a try.

quote:

5. Consider making the values of pageWeights a mutable record of some kind so that you don't have to create new objects all the time.

You're talking about where I create Integer weight = pageWeights.get... ?

geeves
Sep 16, 2004

Sereri posted:

To be fair, those are from the mid to late 90s and haven't been updated ever since. There's stuff in it like "Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools". :psyduck:

This is completely subjective, but I've found the 80 character limit to be a decent rule of thumb for readability. Usually up to about 120 characters is good for me; anything more than that, usually have to scroll to the right and it becomes easy to overlook something when debugging.

geeves
Sep 16, 2004

HFX posted:

I like this one too. Can make it hard to sometimes deal with passing args without storing to a temp variables first.

Java coding conventions are mostly OTBS. I would say violate the hell out 80 character limit though. If you have discriptive names, 80 characters is easy to blow past, and you certainly don't want to go back to the old days of int a,b,c.

As for code cleanup? Is it an embarrassment thing?
'
Also, how did this thread get removed from my bookmarks how do I miss thee.


Sounds crazy, but I've had to debug and run code where the only way to run the code was through a terminal server (80 character lines by 13 lines bitches).

I have a widescreen laptop / Apple monitor as well - it's great and that if I wanted to, I could get to 220 characters in one line at my resolution / font size.

I just prefer to read straight down instead of having to read way across the screen. Like I said, just more a matter of personal preference (thought I have Checkstyle set to 150 characters - more so to accommodate co-workers' styles.

geeves
Sep 16, 2004

Here's really candid interview with James Gosling - some interesting tidbits, including a bit about microSPARC that was a touchscreen LCD in the early 90s - which the people leading that were heavily involved with the iPad later.


http://basementcoders.com/?p=721

http://www.basementcoders.com/transcripts/James_Gosling_Transcript.html

geeves
Sep 16, 2004

Anyone take the IKM tests for Java? Reasonable or should I brush up on obscure stuff?

geeves
Sep 16, 2004

What are some decent frameworks that anyone can recommend I take a look at - I know a bit about what's out there, but I've been mainly stuck in Struts and Apache Jackrabbit / Sling for the last 5 years and really haven't really looked. I have the opportunity to possibly pick something fresh (for me anyway) for a small freelance project I'm taking.

The project is a licensed search-oriented application based on pre-defined content - there are other details to be handled but that is the bulk of the application.

geeves
Sep 16, 2004

Stubb Dogg posted:

I recently worked on a project with Seam 2.2 and it removed lots of usual annoying stuff you have to deal with when doing complex web sites in Java and made it actually enjoyable.

Though at this point it's probably better go straight to Seam 3.0 as it's getting close to release and 3.0 brings portable CDI based on EE 6.

Thanks to everyone who responded - seems it was all for naught though - for at least the demo. I have to convert their DB from... Filemaker Pro to MySQL. 1 million records which will convert to about 25k after properly designing the DB. Unfortunately it seems I'll be doing the proof of concept in PHP since more of my time is being spent converting this database - as well as hosting it myself.

:ughh:

geeves
Sep 16, 2004

This is Struts 2 specific - but <html:select /> won't apply the error css class or style when I add addFieldError(String elementName, String errorText).

Google has failed me and all I've been able to find is discussion about the addFieldError method in general. We don't have any special tags to further handle the struts tags in case of an error.

Edit: figured it out. html:select needs cssErrorClass to be set. Which for some reason is not an attribute that's required for textfields / areas / etc.

geeves fucked around with this message at 17:23 on Feb 2, 2012

geeves
Sep 16, 2004

I am in posted:

I was pleasantly surprised by GSON's ability to fill fully generic containers inside objects correctly without needing to add extra annotations or getters.

Yeah GSON is great. Just make use of their exclusions, especially if you use Hibernate and have associated mappings. It will cry foul about circular dependencies (even if they're not)

geeves
Sep 16, 2004

Struts 2 question (possibly). And it's difficult to explain so I hope this comes across simple to follow.

I have a user-created dynamic form that's built with loading components via ajax (for cardinality, nested form fields, etc.).

All of the fields dynamically added have a name of formfield[N]. N being the row index.

Due to the dynamic ajax loading, for each added field, incrementing is not sequential, but skips by 10 (for more complicated reasons, it cannot be sequential as technically we're loading 2 or 3 fields not just one).

When the form is submitted, it thinks the formfield List size is 100, instead of just 10. That's been fine, until now.

When the form fails validation, (the values are saved no matter what) the formfield List is reloaded in the Action. The Action would clear out and null the formfield List and get a fresh set of the List from the DB.

What is happening now, is that the formfield List still thinks it has 100 members and outputs 100 fields instead of just 10 fields (though logs and debugs say there is only 10 members).

Following the debugger, 10 are loaded and all the data matches up, but instead 100 fields are now displayed once formfield gets to the JSP. It seems that something in Java or Struts is keeping the submitted formfield List in cache / memory / something instead of using the cleared, null'd & fresh formfield List.

I've been stuck on this for most of the day, and really having a hard time asking the right question.

The HTML would look something like this (these have been dynamically added):

code:
<input type="text" name="formfield[0]"/>
<input type="text" name="formfield[10]"/>
<input type="text" name="formfield[20]"/>
<input type="text" name="formfield[30]"/>
In the action

code:
for (Formfield f : formfield) {
    // do validation
    // save value to db
}

formfield = null;

formfield = hibernateManager.getFormfields(formId);
log.info("form field size: " + formfield.size()); // outputs 4 in logs and debugger

And what then gets outputted when needing validation - 30 instead of just 4

code:
<input type="text" name="formfield[0]"/>
...
<input type="text" name="formfield[29]"/>
I've fixed this. There was an <s:action /> that was missing ignoreContextParams="true" so the request scope of formfield from that Action was overwriting what came out of the primary Action.

geeves fucked around with this message at 17:55 on Oct 3, 2012

geeves
Sep 16, 2004

Gravity Pike posted:

Personally, I have a strong preference for JSON unless there is a compelling reason not to. The Gson library is super nice to work with.

code:

class Config {
  public int deviceId;
  public String backendHost;
  public int backendPort;
}

class Packet {
  public int typeId;
  public int objectId;
  public int asn1;
  public Date date;
  public double lat;
  public double lng;
}

class MyInput {
  public Config config;
  public List<Packet> packet;
}

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
MyInput input = gson.fromJson(aString, MyInput.class);
Also works with bean-style objects (setters+getters), but I didn't feel like typing all of those out.

Gson is great. Just be weary if you use with with Hibernate objects (specifically 3.x, haven't used 4.x) as it can get messy with mapped objects that could end up circularly referenced. So make sure you use the @Expose annotation in those cases.

geeves
Sep 16, 2004

Have a Jersey 2 question that I hope is just something small that I'm missing. We're creating an Asset library for users to upload video, docs, etc. for the projectson which they'll be working. I've found similar answers, but those cover most of what I've already done, with the form, method, web.xml and registering MultiPartFeature.class. Here the simple act of implementing a ContainerRequestFilter impedes MULTIPART_FORM_DATA (file upload) from uploading. Returning 415. I'm curious what I'm missing, as I've followed the docs.

Anyway, the following works sans filter and the file uploads as expected and returns what is expected.

code:
public class AssetController extends BaseController {  //Base implements ResourceConfig
    
    public AssetController() {
        super();  // calls super(MultiPartFeature.class);
    }

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public Response uploadAsset(@FormDataParam("file") InputStream uploadedInputStream,
                                @FormDataParam("file") FormDataContentDisposition fileDetail,
                                @Context HttpServletRequest request)
When I attempt to add a Filter - every post, put, delete, etc. continues to work except for Uploading a file with form data- if I remove the @Provider annotation (disabling it), the upload again works. The filter method below is completely blank at the moment, but I'm hoping to use it for some simple permissions authentication

code:
@Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {

    @Context
    private HttpServletRequest request;

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        // this code is currently empty and just writing to logs the header properties, etc.
web.xml just in case:
code:
<servlet>
        <servlet-name>Rest</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>foo.rest</param-value>
        </init-param>
        <init-param>
            <param-name>org.codehaus.jackson.jaxrs</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
Edit: I found the issue, it was looping thorugh some headers and I left in Iterator.remove() which was deleting them causing it not to accept the file :downs:

geeves fucked around with this message at 21:43 on Feb 20, 2015

geeves
Sep 16, 2004

Volguus posted:

On Home Depot there were some articles that were saying that the higher ups were warned years before about the lack of security and potential breaches. And they didn't give a poo poo. How do you think they'll behave when you come and tell them about how well are you going to make this software, and how many good development practices are you going to apply once you present them the price for it?

This is what's infuriating about my company. Our deadlines are set by marketing. Marketing! Some arbitrary date that seems like they're slotting a movie for release than they are a SaaS application. We've been run by marketing and their existential threats for the last few years.

We were hacked through an exploit in Struts - a well known exploit and even we raised it to get time slotted to upgrade (we were denied) . Suddenly we had to basically halt everything to address this because what we said would happened, happened.

It probably doesn't help that we are in one city while the rest of the company is in another. It doesn't even feel that we're part of a company. It feels like we're more a group of independent contractors. Our CTO is in our office, and he knows about all of our complaints and suggestions for improvements; they're well documented. Yet either he is not willing or not able to get the point across to the rest of the executives that some things need to be addressed. The CEO and others rather keep up the charade instead of actually delivering a well-designed and well-tested product. Hell, until the last 6 months we hadn't had a new hire in almost 3 years while the other office nearly tripled in size to meet non-existing demand.

Volguus posted:

I have learned over the years to pick my battles, however. Always try to improve, always try to do the right thing, but look at your surroundings, look at what can you do and let some things go if you have to. Change them if you can on the fly, and if you hit a wall ... make your decision then if you want to continue or not. You are sounding like a stubborn little child who's not going to do his homework unless the exact amount of cake is present on the table. No more, no less. And throws a tantrum until the cake arrives on the table. Good luck, is all I can say.

I've learned just to do whatever I want to improve things when I can and ask for forgiveness later; my boss has basically given me his approval for this approach. It's the only way we get critical things done that aren't new functionality.

geeves
Sep 16, 2004

Volmarias posted:

The same key combo to lock the screen on Ubuntu.

:negative:

You can change it in the keymap to whatever combo you'd prefer.

geeves
Sep 16, 2004

The Laplace Demon posted:

And how you'd actually write the above in Java 8:
Java code:
final List<Dog> dogs = getDogs();
dogs.sort(Comparator.comparing(Dog::getWeight));

My company just upgraded to Java 7. Now I want them to upgrade to 8 because this involves a good portion of what I deal with.

geeves
Sep 16, 2004

Zaphod42 posted:

:siren: A list should never be called "currentItem", that makes no drat sense. Having "currentItem" and "aCurrentItem" is REALLY confusing. Don't do that. :siren:

The list should have a name that makes it clear its a plural collection. "inventory" or "itemList" or "levelItems" or even just "items" is better than "currentItem" which makes it sound like a single Item object instead of an Item array or list. There is not enough obvious difference between "currentItem" and "aCurrentItem" and so those are bad names. They sound like the same object and not a collection versus an object.

My coworker does poo poo like this, as well as using shortened names that are sometimes hard to decipher. I've wasted a lot of time just trying to figure out what things are when using semantic names would make things much quicker.

geeves
Sep 16, 2004

Squashy Nipples posted:

Also, its taking me a while to get used to the Java variable naming conventions, I really miss prefixing with the variable type, as it makes them stand out to me.
Like, lngRow strFileName and poo poo like that. Why do we not do that in Java?

Because we're not writing PHP. :haw:

I still use str / int / dbl as a prefix sometimes when stubbing out methods until I figure out a better name. I especially did this in my earlier days when my methods would be stupidly huge and cumbersome.

geeves
Sep 16, 2004

Gravity Pike posted:

Arcane generics/inheritance typing question:

Java code:
public class Scratch {
    public static void main(String... args) throws Exception {
        final Generic<Generic<Object>> noExtend = null;
        final Generic<Generic<? extends Object>> doesExtend = null;

        doThing(noExtend); //Generic<Generic<Object>> cannot be converted to Generic<Generic<? extends Object>>
        doThing(doesExtend);
    }

    public static class Generic<T> {};

    public static <T> Object doThing(Generic<Generic<? extends T>> arg1) {
        return null;
    }
}
Why can't List<List<Object>> be converted to List<List<? extends Object>>?

I think the problem was that your Scratch class doesn't reference a Record object or have a wikiWikiWiki() method :colbert:

geeves
Sep 16, 2004

Necc0 posted:

This question isn't for me but a coworker of mine was put in a really lovely situation and I want to help*. Does anyone know of a really good Java decompiler? Long story short he's working for a customer who has customizations in their environment that were written 10+ years ago and the original source code has been lost. Don't know if it's because the consultant who wrote originally wrote it sucked rear end and still works here or left 7 years ago or what. We don't have the source code. All we have are the compiled .class files on the server and in the backups. He's been playing around with solutions he found via Google but I've learned that obscure yet generic/old tech problems are probably the worst queries for Google since you only get stuff that was popular back in 2003. In all likelihood there's better stuff out there and I'm guessing if anyone knows it'd be one of you guys.

*Also there's a very good chance I'll be roped in as well in a few months oh god oh god someone please save us

If you're using intellij it is pretty good at decompiling as well right in the editor.

geeves
Sep 16, 2004

I am terrible with Dates and it's the first time I've used Java8 with date formatting.

I have a date string (example: 2015-11-23T12:00:40+00:00) It's pulling a date from a Wordpress formatted date in the <meta property="article:published_time"> tag.

What is the parse string?

I've tried:

yyyy-MM-dd'T'HH:mm:ss
yyyy-MM-dd'T'HH:mm:ssZ
yyyy-MM-dd'T'HH:mm:ssZZ
yyyy-MM-dd'T'HH:mm:ssZZZ

I've been following the patterns here: http://stackoverflow.com/questions/4216745/java-string-to-date-conversion

Code:

code:
public static Date dateParse(String stringDate) throws Exception {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(FULL_DATE); // yyyy-MM-dd'T'HH:mm:ssZZZ
    log.info(stringDate + " | " + FULL_DATE);
    LocalDateTime ldt = LocalDateTime.parse(stringDate, dtf); // ERROR is here

    return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

}

code:
2016-10-16 12:12:45,025 ERROR [main] - TestDateParse:122 - Text '2016-02-11T13:00:40+00:00' could not be parsed at index 19
java.time.format.DateTimeParseException: Text '2016-02-11T13:00:40+00:00' could not be parsed at index 19
	at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
	at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
	at java.time.LocalDateTime.parse(LocalDateTime.java:492)
	at common.util.DateTimeUtil.dateParse(DateTimeUtil.java:33)

geeves fucked around with this message at 17:22 on Oct 16, 2016

geeves
Sep 16, 2004

venutolo posted:

You want something like this (fix any typos if it doesn't compile):

code:
public static OffsetDateTime dateParse(String dateString) {
    return OffsetDateTime.parse(dateString, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
And as mentioned above, don't use Date. Use OffsetDateTime or Instant.

Thanks! That helps a lot! My only problem is that BoundStatement for Cassandra still relies on the java Date object. Typical.

geeves
Sep 16, 2004

hooah posted:

I'm trying to deepen my Java knowledge, so I'm reading through some of the more esoteric (to me) sections of the Java Trails. I've come across lambdas, which are throwing me a bit. Specifically, why is it that in Approach 6, a lambda can be used instead of a Predicate<T> interface? I thought an interface (sort of like a pure abstract class in C++) and a lambda (a function without a name) were two very different things.

I actually just read this last night. I hope I'm wording this correctly, but lambdas / functional programing are inferring the type of object for you without the defining them ala generics. Since Predicates return a Boolean, the interpreter translates what you're doing as that.

quote:

Type inference Predicate < Integer > greaterThan5 = x > x > 5

A Predicate is also a lambda expression that returns a value, unlike the previous ActionListener examples. In this case we’ve used an expression, x > 5 , as the body of the lambda expression. When that happens, the return value of the lambda expression is the value its body evaluates to. You can see from Example 2-12 that Predicate has a single generic type; here we’ve used an Integer . The only argument of the lambda expression implementing Predicate is therefore inferred as an Integer . javac can also check whether the return value is a boolean , as that is the return type of the Predicate method."
― from "Java 8 Lambdas: Pragmatic Functional Programming"

This book overall is pretty good read so far. We just started using Spark, so between this and learning Scala, lambdas and functional programming are the new norm for us.

geeves
Sep 16, 2004

Sedro posted:

java.util.Function is a Java 8 thing. You need to either point to a newer JDK or configure the Java language level. They're both under the menu File -> Project Structure.

Edit: wait, is it java.util.function.Function ?

Other alternative to open project settings is CMD + ; on Mac Not sure on Windows. Pretty sure it's CTRL + ;




geeves fucked around with this message at 03:48 on Oct 25, 2016

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

baquerd posted:

Usually they use a Blackhawk on ISIS, not the Apache.

Thank you. I couldn't think of a good pun for this.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply