I’m working on UCM project and the workflow is to read on a metadata filed (xComments , which will have SSN #’s separated by commas) and submit a separate document for each SSN found in the xComments and replace the SSN’s with the custom metadata filed Name xSSN.
Just to be brief:
If document “A” has xComments filed value 1,2,3 and xSSN value “ multiple” then I want my script/java code to create “Document A”, “Document B”, “Document c”, having a xSSN filed 1,2 and 3
public class ContentCheckInHandler implements FilterImplementor{
public int doFilter(Workspace ws, DataBinder binder, ExecutionContext cxt)
throws DataException, ServiceException
{
//boolean isCheckin = StringUtils.convertToBool(binder.getLocal("isCheckin"), false);
//boolean isNew = StringUtils.convertToBool(binder.getLocal("isNew"), false);
String dDocType = binder.getLocal("dDocType");
String xRegion = binder.getLocal("xRegion");
String xSSN = binder.getLocal("xSSN");
String xComments = binder.getLocal("xComments");
String [] SSNListSeparate = xComments.split(",");
int[]convertxComments = new int[xComments.length()];
boolean chkxComments = false;
String primaryFile = getFilePath(binder, "primaryFile");
if(xSSN == "Multiple" || xSSN == "multiple" && xComments.length() > 0)
{
for(int i = 0; i < SSNListSeparate.length; i++)
{
convertxComments[i] = Integer.parseInt(SSNListSeparate[i]);
DataBinder b = new DataBinder();
b.putLocal("dID", binder.getLocal("dID"));
b.putLocal("dDocName", binder.getLocal("dDocName"));
b.putLocal("xAccountNumber", binder.getLocal("xAccountNumber"));
b.putLocal("xSSN",SSNListSeparate[i]);
b.putLocal("xRegion", xRegion);
b.putLocal("xFirstName", "");
b.putLocal("xLastName", "");
b.putLocal("xFSADocType", binder.getLocal("xFSADocType"));
b.putLocal("xPLDocType", binder.getLocal("xPLDocType"));
b.putLocal("xDocSource", binder.getLocal("xDocSource"));
ws.execute("CHECKIN_NEW_SUB", b);
}
}
else
{
chkxComments = false;
SystemUtils.trace("TrainingDocument", "SSN value: " + xSSN);//just for testing
}
return CONTINUE;
}
public String getFilePath(DataBinder binder, String fileKey)
throws DataException
{
return ServerFileUtils.getTemporaryFilePath(binder, fileKey);
}
}
Related
I'm having a trouble passing the value of error i get when im returning the results of a table.
I have a method in my ServiceImpl class which return results for the table and also counts the amount of errors.
public List<Flow> getAllProcessContextWithCriteriaAndFlowCode(
String startDate, String endDate, String flowCode) {
List<FlowDto> flowDtos = new ArrayList<>(500);
flowDtos = processContextRepository
.fetch(startDate,
endDate, flowCode);
List<Flow> flows = new ArrayList();
// bodyguard
if (flowDtos == null || flowDtos.size() == 0) {
return flows;
}
int counter = 0;
StringBuilder idFonctionnelBuilder = new StringBuilder();
FlowDto currentFlowDto = null;
FlowState flowState = new FlowState();
FlowDto nextFlowDto = null;
Flow flowTemp = null;
Map<String, String> mapFlowIdsAndIdF = new HashMap<>();
int iNbreError = 0;
String sTempError = "";
for (int i = 0; i < flowDtos.size(); i++) {
currentFlowDto = flowDtos.get(i);
if ((i + 1) < flowDtos.size()) {
nextFlowDto = flowDtos.get(i + 1);
if (((nextFlowDto.getFlowId()
.equals(currentFlowDto.getFlowId())))) {
idFonctionnelBuilder.append(currentFlowDto.getIdf() + ", ");
continue;
} else {
flowTemp = new Flow();
flowTemp.setFlowId(currentFlowDto.getFlowId());
flowTemp.setLogRole(currentFlowDto.getLogRole());
Date date = null;
try {
date = inputFormat.parse(currentFlowDto
.getContextTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flowTemp.setContextTime(outputFormat.format(date));
if (currentFlowDto.getLogRole() != null) {
iNbreError++;
flowTemp.setNbreError(iNbreError);
} else {
flowTemp.setNbreError(iNbreError);
}
flowTemp.setNbreError(iNbreError);
flows.add(flowTemp);
}
} else {
flowTemp = new Flow();
if (currentFlowDto.getLogRole() != null) {
iNbreError++;
flowTemp.setNbreError(iNbreError);
} else {
flowTemp.setNbreError(iNbreError);
}
flowTemp.setContextTime(outputFormat.format(date));
flows.add(flowTemp);
}
}
LOGGER.info("[ getAllProcessContextWithCriteriaAndFlowCode ] iNbreError : "
+ iNbreError);
getNbreError(iNbreError);
return flows;
}
Then i have another method in the same class ServiceImpl who get the number of errors and set it in a variable, the result print is always the right one here.
public int getNbreError( int iNbreError){
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(iNbreError);
setCountError(iNbreError);
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(countError);
return countError;
}
What i want to do is send this value(counterror) to my RestController which is in another class called RestController so i can send it to my angular front
#GetMapping(value = "/nbreError")
public int getCountError() {
FMServiceImpl flows = new FMServiceImpl();
int countError = 0;
int iNbreError = 0;
return fmService.getNbreError( iNbreError);
}
}
Actually the result is always 0.
Thanks for your any help or advice :)
Don't use getMethod to modify data, check principle Command–query separation (CQS)
Don't create FMServiceImpl manually, Inject FMServiceImpl as dependence to your controller. in spring, Service keeps the state by default.
I'm fairly new into the apache spark technology and I'm having some problems while trying to analyze data I'm pulling from my files.
I have big list of genes information, and I'm pulling that information to a RDD, so far so good.
JavaRDD<Gene> inputfile = sc.textFile(logFile).map(
new Function<String, Gene>() {
#Override
public Gene call(String line) throws Exception {
String[] values = line.split("\t");
Gene gen = null;
//We are only interested in genes;
if( values.length > 2 && values[2].equalsIgnoreCase("gene") && !line.contains("#")){
String[] infoGene = values[8].split(";");
String geneId = StringUtils.substringBetween(infoGene[0], "\"");
String geneType = StringUtils.substringBetween(infoGene[2], "\"");
String geneName = StringUtils.substringBetween(infoGene[4], "\"");
gen = new Gene(geneName,values[3],values[4]);
return gen;
}
return gen;
}
}
).filter(new Function<Gene, Boolean>() {
#Override
public Boolean call(Gene gene) throws Exception {
if(gene == null)
return false;
else
return true;
}
});
The Gene class:
public class Gene implements Serializable{
String firstBp;
String lastBp;
String name;
public Gene(String name, String firstBp, String lastBp) {
this.name = name;
this.firstBp = firstBp;
this.lastBp = lastBp;
}
public String getFirstBp() {
return firstBp;
}
public String getLastBp() {
return lastBp;
}
public String getName() {
return name;
}
public String toString(){
return name + " " + firstBp + " " + lastBp;
}}
The problem starts here, I need to analyze if 2 Genes overlay, and for that I've made this simple utility function:
public static Boolean isOverlay(Gene gene1, Gene gene2){
int gene1First = Integer.parseInt(gene1.getFirstBp());
int gene1Last = Integer.parseInt(gene1.getLastBp());
int gene2First = Integer.parseInt(gene2.getFirstBp());
int gene2Last = Integer.parseInt(gene2.getLastBp());
if(gene2First >= gene1First && gene2First <= gene1Last) // FirstBp - Gene2 inside
return true;
else if (gene2Last >= gene1First && gene2Last <= gene1Last) // LastBP - Gene2 inside
return true;
else if (gene1First >= gene2First && gene1First <= gene2Last) // FirstBp - Gene1 inside
return true;
else if (gene1Last >= gene2First && gene1Last <= gene2Last) // LastBP - Gene1 inside
return true;
else
return false;
}
Now what I'm doing and I think is wrong is transforming the RDD Object into a list by doing:
List<Gene> genesList = inputfile.collect();
And iterate over that list to check if there are overlays and save to the file the results which is taking ages because I'm not using spark.
List<OverlayPair> overlayPairList= new ArrayList<OverlayPair>();
List<String> visitedGenes = new ArrayList<String>();
for (Gene gene1 : genesList){
for (Gene gene2 : genesList) {
if (gene1.getName().equalsIgnoreCase(gene2.getName()) || visitedGenes.contains(gene2.getName())) {
continue;
}
if (isOverlay(gene1, gene2))
overlayPairList.add(new OverlayPair(gene1.getName(), gene2.getName()));
}
visitedGenes.add(gene1.getName());
}
JavaRDD<OverlayPair> overlayFile = sc.parallelize(overlayPairList);
//Export the results to the file
String outputDirectory = "/Users/joaoalmeida/Desktop/Dissertacao/sol/data/mitocondrias/feup-pp/project/data/output/overlays";
overlayFile.coalesce(1).saveAsTextFile(outputDirectory);
The Overlay pair is basically an object with the 2 genes name.
Is there anyway to do this 2nd part while taking advantage of spark? Because the time complexity of those 2 for's its to big for the amount of data I currently have.
Yes, there is, you have to use RDD.cartesian function to get all the pairs and then you can basically apply the function you wrote.
I am quite satisfied with the GUI elements of JavaFX; however, the ListView control offers no alphanumeric keyboard navigability by default. The arrow keys work, but jumping to items beginning with "a" by typing the respective letter key does not.
Is this feature built-in? If not, how would you implement it?
I implemented it this way:
private String searchText = "";
private long searchTextLastTyped = 0;
private int searchTextSkip = 0;
...
listView.setOnKeyTyped(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCharacter() != null) {
//in case of same character typed more times = search next occurence
if (searchText.equals(event.getCharacter())) {
searchTextSkip++;
} else {
//in case typing more characters relatively quickly = append character
if (System.currentTimeMillis() - searchTextLastTyped < 1000) {
searchText += event.getCharacter();
//typing new character after pause = new search
} else {
searchText = event.getCharacter();
}
}
searchTextLastTyped = System.currentTimeMillis();
boolean found = false;
int skipped = 0;
for (T item : getItems()) {
if (getTextValue(item).toUpperCase().startsWith(searchText.toUpperCase())) {
if (searchTextSkip > skipped) {
skipped++;
continue;
}
setValue(item);
found = true;
break;
}
}
//reset to first occurence
if (!found) {
searchTextSkip = 0;
}
}
}
});
Here's a class that can be dropped in, which has a few minor tweaks to the code above:
private static final class ListViewHandler<T> {
/**
* Amount of time to wait between key presses that typing a subsequent
* key is considered part of the same search, in milliseconds.
*/
private static final int RESET_DELAY_MS = 1250;
private String mNeedle = "";
private int mSearchSkip = 0;
private long mLastTyped = currentTimeMillis();
private final ListView<T> mHaystack;
private ListViewHandler( final ListView<T> listView ) {
mHaystack = listView;
}
private void handle( final KeyEvent key ) {
var ch = key.getText();
if( ch == null || ch.isEmpty() ||
key.getCode() == ESCAPE || key.getCode() == ENTER ) {
return;
}
ch = ch.toUpperCase();
if( mNeedle.equals( ch ) ) {
mSearchSkip++;
}
else {
mNeedle = currentTimeMillis() - mLastTyped > RESET_DELAY_MS
? ch : mNeedle + ch;
}
mLastTyped = currentTimeMillis();
boolean found = false;
int skipped = 0;
for( final T item : mHaystack.getItems() ) {
final var straw = item.toString().toUpperCase();
if( straw.startsWith( mNeedle ) ) {
if( mSearchSkip > skipped ) {
skipped++;
continue;
}
mHaystack.getSelectionModel().select( item );
final int index = mHaystack.getSelectionModel().getSelectedIndex();
mHaystack.getFocusModel().focus( index );
mHaystack.scrollTo( index );
found = true;
break;
}
}
if( !found ) {
mSearchSkip = 0;
}
}
}
Example usage:
final var listView = // ... get the ListView object;
final var handler = new ListViewHandler<>( listView );
listView.setOnKeyTyped( handler::handle );
In my below code, colData stores JSON String. Sample example for colData-
{"lv":[{"v":{"price":70.0,"userId":419},"cn":3},
{"v":{"price":149.99,"userId":419},"cn":3},
{"v":{"price":54.95,"userId":419},"cn":3}],
"lmd":20130206212543}
Now I am trying to match id value with userId value in the above JSON String. I am getting id value from a different source.
Meaning if id value is 419 then in the above JSON String userId value should also be 419. And in the JSON String, it might be possible there are lot of userId values so all the userId values should be matching with id. If any of them doesn't matches then log the exception.
So I was trying something like this-
final int id = generateRandomId(random);
for (String str : colData) {
if (!isJSONValid(str, id)) {
// log the exception here
LOG.error("Invalid JSON String " +str+ "with id" +id);
}
}
public boolean isJSONValid(final String str, final int id) {
boolean valid = false;
try {
final JSONObject obj = new JSONObject(str);
final JSONArray geodata = obj.getJSONArray("lv");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
JSONObject menu = person.getJSONObject("v");
if(menu.getInt("userId") == id) {
valid = true;
}
}
} catch (JSONException ex) {
valid = false;
}
return valid;
}
As per my understanding it looks like I can make isJSONValid method more cleaner. In my above isJSONValid method as I am repeating some stuff which I shouldn't be doing. Can anyone help me out how to make this more cleaner if I have missed anything. I will be able to learn some more stuff. Thanks for the help
You can initialize valid = true and set it to false when you find a non-valid userId and immediately fail:
public boolean isJSONValid(final String str, final int id) {
boolean valid = true;
try {
final JSONObject obj = new JSONObject(str);
final JSONArray geodata = obj.getJSONArray("lv");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
JSONObject menu = person.getJSONObject("v");
if(menu.getInt("userId") != id) {
valid = false;
break;
}
}
} catch (JSONException ex) {
valid = false;
}
return valid;
}
This way you iterate through all array's elements only if all are valid, which is the only case you actually have to.
The question says everything. When I am printing an Attribute it is:
cn: WF-008-DAM-PS
The code snippet is:
private void searchGroup() throws NamingException {
NamingEnumeration<SearchResult> searchResults = getLdapDirContext().search(groupDN, "(objectclass=groupOfUniqueNames)", getSearchControls());
String searchGroupCn = getCNForBrand(m_binder.getLocal("brandId"), m_binder.getLocal("brandName"));
Log.info(searchGroupCn);
while (searchResults.hasMore()) {
SearchResult searchResult = searchResults.next();
Attributes attributes = searchResult.getAttributes();
Attribute groupCn = attributes.get("cn");
if(groupCn != null) {
Log.info(groupCn.toString());
}
}
}
How can I only get the value that is: WF-008-DAM-PS, that is without the key portion?
Regards.
The solution is:
Attribute groupCn = attributes.get("cn");
String value = groupCn.get();
Invoke the getValue() method or the getValue(int) method.
General
Let's say that we have:
Attributes attributes;
Attribute a = attributes.get("something");
if(a.size() == 1)
then you can use a.get() or a.get(0) to get the unique value
if(a.size() > 1)
iterate through all the values:
for ( int i = 0 ; i < a.size() ; i++ ) {
Object currentVal = a.get(i);
// do something with currentVal
}
If you use a.get() here, it will return only the first value, because its internal implementation (in BasicAttribute) looks like this:
public Object get() throws NamingException {
if (values.size() == 0) {
throw new NoSuchElementException("Attribute " + getID() + " has no value");
} else {
return values.elementAt(0);
}
}
Both methods (get(int) and get()) throws a NamingException.
Practical example
(when the Attribute instance has multiple values)
LdapContext ctx = new InitialLdapContext(env, null);
Attributes attributes = ctx.getAttributes("", new String[] { "supportedSASLMechanisms" });
System.out.println(attributes); // {supportedsaslmechanisms=supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5}
Attribute a = atts.get("supportedsaslmechanisms");
System.out.println(a); // supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5
System.out.println(a.get()); // GSSAPI
for (int i = 0; i < a.size(); i++) {
System.out.print(a.get(i) + " "); // GSSAPI EXTERNAL DIGEST-MD5
}
This worked:(checking attribute present or not before fetching attribute value)
Attributes attributes = searchResult.getAttributes();
Attribute mail = attributes.get("mail");
if (mail != null)
{
System.out.println(" Mail-id value from LDAP :"+mail.get());
}