file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Unique.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Unique.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Recursive.java * */ package org.wandora.query2; import java.util.HashSet; import java.util.NoSuchElementException; /** * * @author olli */ public class Unique extends Directive implements DirectiveUIHints.Provider { private Directive directive; public Unique(){} public Unique(Directive directive){ this.directive=directive; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Unique.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), }, Directive.getStandardAddonHints(), "Unique", "Structure"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { return new UniqueIterator(context,input); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } private class UniqueIterator extends ResultIterator { public QueryContext context; public ResultRow input; public ResultIterator iter; public HashSet<ResultRow> included; public ResultRow next; public UniqueIterator(QueryContext context,ResultRow input) throws QueryException { this.context=context; this.input=input; iter=directive.queryIterator(context, input); included=new HashSet<ResultRow>(); } @Override public void dispose() throws QueryException { iter.dispose(); included=null; } @Override public boolean hasNext() throws QueryException { if(next!=null) return true; while(iter.hasNext()) { next=iter.next(); if(included.add(next)) return true; } next=null; return false; } @Override public ResultRow next() throws QueryException, NoSuchElementException { if(hasNext()){ ResultRow ret=next; next=null; return ret; } else throw new NoSuchElementException(); } @Override public void reset() throws QueryException { iter.reset(); included=new HashSet<ResultRow>(); next=null; } } }
3,681
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Static.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Static.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Static.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.Arrays; /** * * @author olli */ public class Static extends Directive implements DirectiveUIHints.Provider { private ArrayList<ResultRow> result; public Static(){ this.result=new ArrayList<ResultRow>(); } public Static(ArrayList<ResultRow> result){ this.result=result; } public Static(ResultRow result){ this.result=new ArrayList<ResultRow>(); this.result.add(result); } public Static(ResultRow[] result){ this.result=new ArrayList<ResultRow>(); this.result.addAll(Arrays.asList(result)); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Static.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, "") // result row type is not yet supported // new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ // new DirectiveUIHints.Parameter(ResultRow.class, true, "row") // }, "") }, Directive.getStandardAddonHints(), "Static", "Primitive"); return ret; } @Override public ArrayList<ResultRow> query(QueryContext context, ResultRow input) throws QueryException { return result; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { if(result.size()==1) return result.get(0).toIterator(); else return super.queryIterator(context, input); } @Override public boolean isStatic(){ return true; } }
2,584
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Exists.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Exists.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Exists.java * * */ package org.wandora.query2; /** * * @author olli */ public class Exists extends WhereDirective implements DirectiveUIHints.Provider { private Directive directive; public Exists(){} public Exists(Directive directive){ this.directive=directive; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Exists.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, "") }, Directive.getStandardAddonHints(), "Exists", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public boolean includeRow(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); if(iter.hasNext()){ iter.dispose(); return true; } else { iter.dispose(); return false; } } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
2,365
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Regex.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Regex.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Regex.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author olli */ public class Regex extends WhereDirective implements DirectiveUIHints.Provider { public static final int MODE_MATCH=1; public static final int MODE_GLOBAL=2; public static final int MODE_ICASE=4; private Operand regex; private Operand replace; private boolean match; private boolean global; private boolean icase; private Pattern pattern; public Regex(){} public Regex(Object regex,Object replace,int mode){ this.regex=new Operand(regex); this.replace=(replace==null?null:new Operand(replace)); match=((mode&MODE_MATCH)>0); global=((mode&MODE_GLOBAL)>0); icase=((mode&MODE_ICASE)>0); } public Regex(String regex,String replace){ this(regex,replace,MODE_GLOBAL); } public Regex(String regex){ this(regex,null,MODE_MATCH|MODE_GLOBAL); } public Regex(String regex,int mode){ this(regex,null,MODE_MATCH|mode); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Regex.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, false, "regex") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, false, "regex"), new DirectiveUIHints.Parameter(Integer.class, false, "mode") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, false, "regex"), new DirectiveUIHints.Parameter(String.class, false, "replace") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Operand.class, false, "regex"), new DirectiveUIHints.Parameter(Operand.class, false, "replace"), new DirectiveUIHints.Parameter(Integer.class, false, "mode") }, "") }, Directive.getStandardAddonHints(), "Regex", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { regex.endQuery(context); if(replace!=null) replace.endQuery(context); pattern=null; } @Override public boolean startQuery(QueryContext context) throws QueryException { return regex.startQuery(context)&(replace==null?true:replace.startQuery(context)); } private ResultRow makeRow(ResultRow original,String role,String replacement){ ArrayList<String> newRoles=new ArrayList<String>(); ArrayList<Object> newValues=new ArrayList<Object>(); for(int i=0;i<original.getNumValues();i++){ String r=original.getRole(i); Object v=original.getValue(i); if(r.equals(role)) v=replacement; newRoles.add(r); newValues.add(v); } return new ResultRow(newRoles, newValues,original.getActiveColumn(),true); } @Override public ResultRow processRow(QueryContext context,ResultRow input) throws QueryException { if(pattern==null || !regex.isStatic()){ String re=regex.getOperandString(context, input); pattern=Pattern.compile(re,icase?Pattern.CASE_INSENSITIVE:0); } if(replace==null) { if(includeRow(context,input)) return input; else return null; } else { Object value=input.getActiveValue(); String role=input.getRole(input.getActiveColumn()); if(value==null){ if(!match) return input; else return null; } String s=value.toString(); Matcher m=pattern.matcher(s); if(global) s=m.replaceAll(replace.getOperandString(context, input)); else s=m.replaceFirst(replace.getOperandString(context, input)); if(match){ try{ m.group(); return makeRow(input,role,s); }catch(IllegalStateException e){ return null; } } else return makeRow(input,role,s); } } @Override public boolean includeRow(QueryContext context, ResultRow input) throws QueryException { if(replace!=null) throw new QueryException("Regex directive cannot be used as WhereDirective with replace string."); Object value=input.getActiveValue(); String role=input.getRole(input.getActiveColumn()); if(value==null) return false; String s=value.toString(); Matcher m=pattern.matcher(s); if(global) { if(m.matches()) return true; } else { if(m.find()) return true; } return false; } }
6,086
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Or.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Or.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Or.java * * */ package org.wandora.query2; /** * * @author olli */ public class Or extends WhereDirective implements DirectiveUIHints.Provider { private WhereDirective[] directives; public Or(){} public Or(WhereDirective[] directives){ this.directives=directives; } public Or(WhereDirective d1,WhereDirective d2){ this(new WhereDirective[]{d1,d2}); } public Or(WhereDirective d1,WhereDirective d2,WhereDirective d3){ this(new WhereDirective[]{d1,d2,d3}); } public Or(WhereDirective d1,WhereDirective d2,WhereDirective d3,WhereDirective d4){ this(new WhereDirective[]{d1,d2,d3,d4}); } public Or(WhereDirective d1,WhereDirective d2,WhereDirective d3,WhereDirective d4,WhereDirective d5){ this(new WhereDirective[]{d1,d2,d3,d4,d5}); } public Or(WhereDirective d1,WhereDirective d2,WhereDirective d3,WhereDirective d4,WhereDirective d5,WhereDirective d6){ this(new WhereDirective[]{d1,d2,d3,d4,d5,d6}); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Or.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, true, "whereDirective") }, "") }, Directive.getStandardAddonHints(), "Or", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { for(int i=0;i<directives.length;i++){directives[i].endQuery(context);} } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean r=true; for(int i=0;i<directives.length;i++){r&=directives[i].startQuery(context);} return r; } @Override public boolean includeRow(QueryContext context, ResultRow input) throws QueryException { boolean cond=false; for(int i=0;i<directives.length;i++){ if(directives[i].includeRow(context, input)) return true; } return false; } @Override public String debugStringParams(String indent) { return debugStringInner(directives,indent); } }
3,144
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Types.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Types.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Types.java * * */ package org.wandora.query2; import java.util.ArrayList; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class Types extends Directive implements DirectiveUIHints.Provider { public Types(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Types.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, "") }, Directive.getStandardAddonHints(), "Types", "Topic map"); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); for(Topic t : ((Topic)o).getTypes()){ ret.add(input.addValue(DEFAULT_COL, t)); } return new ResultIterator.ListIterator(ret); }catch(TopicMapException tme){ throw new QueryException(tme); } } }
2,322
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
As.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/As.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Compare.java * */ package org.wandora.query2; import java.util.ArrayList; /** * * @author olli */ public class As extends Directive implements DirectiveUIHints.Provider { private String original; private String newRole; public As(){}; public As(String newRole){ this.newRole=newRole; } public As(String original,String newRole){ this.original=original; this.newRole=newRole; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(As.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, false, "newRole"), }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, false, "originalRole"), new DirectiveUIHints.Parameter(String.class, false, "newRole") }, "") }, Directive.getStandardAddonHints(), "As", "Framework"); return ret; } public String getOriginalRole(){ return original; } public String getNewRole(){ return newRole; } @Override public ArrayList<ResultRow> query(QueryContext context,ResultRow input) throws QueryException { ArrayList<String> roles=new ArrayList<String>(input.getRoles()); ArrayList<Object> values=new ArrayList<Object>(input.getValues()); int i; if(original==null) i=input.getActiveColumn(); else { i=roles.indexOf(original); if(i==-1) throw new QueryException("Trying to change role \""+original+"\" to \""+newRole+"\" in result row but it doesn't exist."); } int j=roles.indexOf(newRole); if(j>=0 && i!=j) { // throw new QueryException("Role \""+newRole+"\" already exists."); roles.remove(j); values.remove(j); if(j<i) i--; } roles.set(i, newRole); return new ResultRow(roles,values,i,true).toList(); } public String debugStringParams(){ if(original!=null) return "\""+original+"\",\""+newRole+"\""; else return "\""+newRole+"\""; } }
3,191
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Union.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Union.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Union.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.NoSuchElementException; /** * * @author olli */ public class Union extends Directive implements DirectiveUIHints.Provider { private Directive[] directives; private ArrayList<String> staticRoles; private boolean useActive=false; public Union(){this(new Directive[0]);} public Union(Directive[] directives){ this.directives=directives; } public Union(Directive d1){this(new Directive[]{d1});} public Union(Directive d1,Directive d2){this(new Directive[]{d1,d2});} public Union(Directive d1,Directive d2,Directive d3){this(new Directive[]{d1,d2,d3});} public Union(Directive d1,Directive d2,Directive d3,Directive d4){this(new Directive[]{d1,d2,d3,d4});} @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Union.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, true, "directives") }, "") }, Directive.getStandardAddonHints(), "Union", "Structure"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { for(Directive d : directives){ d.endQuery(context); } } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean r=true; for(Directive d : directives){ r&=d.startQuery(context); } return r; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { if(staticRoles==null && !useActive) return new UnionIterator(context,input); else return new StaticUnionIterator(context,input); } @Override public boolean isStatic(){ for(Directive d : directives){ if(!d.isStatic()) return false; } return true; } public Union ofActiveRole(){ useActive=true; return this; } public void ofRoles(String ... role){ staticRoles=new ArrayList<String>(); for(String r : role){ staticRoles.add(r); } } public void ofRoles(String r1){ ofRoles(new String[]{r1}); } public void ofRoles(String r1,String r2){ ofRoles(new String[]{r1,r2}); } public void ofRoles(String r1,String r2,String r3){ ofRoles(new String[]{r1,r2,r3}); } public void ofRoles(String r1,String r2,String r3,String r4){ ofRoles(new String[]{r1,r2,r3,r4}); } @Override public String debugStringParams(String indent) { return debugStringInner(directives,indent); } private class StaticUnionIterator extends ResultIterator { public QueryContext context; public ResultRow input; public ResultIterator[] iterators; public int currentDirective=-1; public ResultRow nextRow; public StaticUnionIterator(QueryContext context,ResultRow input) throws QueryException { this.context=context; this.input=input; iterators=new ResultIterator[directives.length]; } private ResultRow makeRow(ResultRow row) throws QueryException { if(useActive) return new ResultRow(row.getActiveValue()); else { ArrayList<Object> values=new ArrayList<Object>(staticRoles.size()); ArrayList<String> rowRoles=row.getRoles(); for(int i=0;i<staticRoles.size();i++){ int ind=rowRoles.indexOf(staticRoles.get(i)); Object v=null; if(ind>=0) v=row.getValue(ind); values.add(v); } return new ResultRow(staticRoles,values,0,true); } } @Override public void dispose() throws QueryException { for(int i=0;i<iterators.length;i++){ if(iterators[i]==null) break; iterators[i].dispose(); } } @Override public boolean hasNext() throws QueryException { if(nextRow!=null) return true; while( currentDirective<directives.length && (currentDirective==-1 || !iterators[currentDirective].hasNext()) ) { currentDirective++; if(currentDirective>=directives.length) break; if(iterators[currentDirective]==null) iterators[currentDirective]=directives[currentDirective].queryIterator(context, input); } if(currentDirective>=directives.length) return false; nextRow=makeRow(iterators[currentDirective].next()); return true; } @Override public ResultRow next() throws QueryException, NoSuchElementException { if(hasNext()) { ResultRow temp=nextRow; nextRow=null; return temp; } else throw new NoSuchElementException(); } @Override public void reset() throws QueryException { for(int i=0;i<currentDirective;i++){ iterators[i].reset(); } currentDirective=-1; nextRow=null; } } private class UnionIterator extends ResultIterator { public QueryContext context; public ResultRow input; public ResultRow[] firstRows; public ResultIterator[] iterators; public int currentDirective; public ArrayList<String> roles; public ResultRow nextRow; public UnionIterator(QueryContext context,ResultRow input) throws QueryException { this.context=context; this.input=input; currentDirective=-1; LinkedHashSet<String> rolesHash=new LinkedHashSet<String>(); firstRows=new ResultRow[directives.length]; iterators=new ResultIterator[directives.length]; for(int i=0;i<directives.length;i++){ iterators[i]=directives[i].queryIterator(context, input); if(iterators[i].hasNext()) { firstRows[i]=iterators[i].next(); for(String role : firstRows[i].getRoles()){ rolesHash.add(role); } } } roles=new ArrayList<String>(rolesHash); } private ResultRow makeRow(ResultRow row) throws QueryException { ArrayList<Object> values=new ArrayList<Object>(roles.size()); ArrayList<String> rowRoles=row.getRoles(); for(int i=0;i<roles.size();i++){ int ind=rowRoles.indexOf(roles.get(i)); Object v=null; if(ind>=0) v=row.getValue(ind); values.add(v); } return new ResultRow(roles,values,0,true); } @Override public void dispose() throws QueryException { for(int i=0;i<iterators.length;i++){ iterators[i].dispose(); } } @Override public boolean hasNext() throws QueryException { if(nextRow!=null) return true; while(currentDirective<firstRows.length && (currentDirective<0 || (firstRows[currentDirective]==null && !iterators[currentDirective].hasNext())) ) { currentDirective++; } if(currentDirective>=firstRows.length) return false; if(firstRows[currentDirective]!=null){ nextRow=makeRow(firstRows[currentDirective]); firstRows[currentDirective]=null; } else nextRow=makeRow(iterators[currentDirective].next()); return true; } @Override public ResultRow next() throws QueryException, NoSuchElementException { if(hasNext()) { ResultRow temp=nextRow; nextRow=null; return temp; } else throw new NoSuchElementException(); } @Override public void reset() throws QueryException { LinkedHashSet<String> rolesHash=new LinkedHashSet<String>(); for(int i=0;i<iterators.length;i++){ iterators[i].reset(); if(iterators[i].hasNext()) { firstRows[i]=iterators[i].next(); for(String role : firstRows[i].getRoles()){ rolesHash.add(role); } } else firstRows[i]=null; } roles=new ArrayList<String>(rolesHash); currentDirective=-1; nextRow=null; } } }
10,019
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
If.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/If.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * If.java * * */ package org.wandora.query2; import java.util.ArrayList; /** * * @author olli */ public class If extends Directive implements DirectiveUIHints.Provider { private Directive cond; private Directive then; private Directive els; public If(){} public If(Directive cond,Directive then,Directive els){ this.cond=cond; this.then=then; this.els=els; } public If(WhereDirective cond,Directive then){ this(cond,then,new Empty()); } public If(WhereDirective cond){ this(cond,new Identity(),new Empty()); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(If.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "condition") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "condition"), new DirectiveUIHints.Parameter(Directive.class, false, "then") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "condition"), new DirectiveUIHints.Parameter(Directive.class, false, "then"), new DirectiveUIHints.Parameter(Directive.class, false, "else") }, ""), }, Directive.getStandardAddonHints(), "If", "Structure"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { cond.endQuery(context); then.endQuery(context); els.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean r=true; r&=cond.startQuery(context); r&=then.startQuery(context); r&=els.startQuery(context); return r; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator condIter=cond.queryIterator(context, input); boolean dispose=true; try{ if(condIter.hasNext()){ if(then instanceof COND) { dispose=false; return condIter; } else return then.queryIterator(context, input); } else{ if(els instanceof COND){ dispose=false; return condIter; } else return els.queryIterator(context, input); } } finally{ if(dispose) condIter.dispose(); } } @Override public String debugStringParams(String indent) { return debugStringInner(new Directive[]{cond,then,els},indent); } public static class COND extends Directive implements DirectiveUIHints.Provider { // this class serves only as a marker, it is never actually queried public COND(){} @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(If.COND.class,new DirectiveUIHints.Constructor[]{ }, Directive.getStandardAddonHints(), "If.COND", "Structure"); return ret; } @Override public ArrayList<ResultRow> query(QueryContext context, ResultRow input) throws QueryException { throw new QueryException("If.COND should not be queried directly."); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { throw new QueryException("If.COND should not be queried directly."); } } }
4,897
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SubjectIdentifiers.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/SubjectIdentifiers.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SubjectIdentifiers.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.Collection; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SubjectIdentifiers extends Directive implements DirectiveUIHints.Provider { public void SubjectIdentifiers(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Roles.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, "") }, Directive.getStandardAddonHints(), "SubjectIdentifiers", "Topic map"); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return new ResultIterator.EmptyIterator(); try{ if(!(o instanceof Topic)){ TopicMap tm=context.getTopicMap(); o=tm.getTopic(o.toString()); if(o==null) return new ResultIterator.EmptyIterator(); } Collection<Locator> sis=((Topic)o).getSubjectIdentifiers(); ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); for(Locator si : sis){ ret.add(input.addValue(Directive.DEFAULT_COL,si.toString())); } return new ResultIterator.ListIterator(ret); }catch(TopicMapException tme){ throw new QueryException(tme); } } }
2,526
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WhereDirective.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/WhereDirective.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * WhereDirective.java * */ package org.wandora.query2; /** * * @author olli */ public abstract class WhereDirective extends FilterDirective { public ResultRow processRow(QueryContext context,ResultRow input) throws QueryException { if(includeRow(context,input)) return input; else return null; } public abstract boolean includeRow(QueryContext context,ResultRow input) throws QueryException; public WhereDirective and(WhereDirective d){ return new And(this,d); } public WhereDirective and(String c1,String comp,String c2){ return and(new Compare(c1,comp,c2)); } public WhereDirective or(WhereDirective d){ return new Or(this,d); } public WhereDirective or(String c1,String comp,String c2){ return or(new Compare(c1,comp,c2)); } public WhereDirective not(){ return new Not(this); } }
1,706
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Last.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Last.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Last.java * */ package org.wandora.query2; import java.util.ArrayList; import java.util.LinkedList; /** * * @author olli */ public class Last extends Directive implements DirectiveUIHints.Provider { private Directive directive; private int count; public Last(){} public Last(int count,Directive directive){ this.count=count; this.directive=directive; } public Last(Directive directive){ this(1,directive); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Last.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Integer.class, false, "count"), new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, "") }, Directive.getStandardAddonHints(), "Last", "Structure"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); if(count>1){ LinkedList<ResultRow> history=new LinkedList<ResultRow>(); while(iter.hasNext()){ history.add(iter.next()); while(history.size()>count) history.removeFirst(); } return new ResultIterator.ListIterator(new ArrayList<ResultRow>(history)); } else{ ResultRow last=null; while(iter.hasNext()) last=iter.next(); if(last==null) return new ResultIterator.EmptyIterator(); else return last.toIterator(); } } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
3,211
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Directive.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Directive.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Directive.java * */ package org.wandora.query2; import java.util.ArrayList; import java.util.List; import org.wandora.query2.DirectiveUIHints.Addon; import org.wandora.query2.DirectiveUIHints.Parameter; /** * * Subclasses must override at least one of query or queryIterator. Default * implementation has them calling eachother. Whenever the result can * meaningfully be delivered in smaller chunks, iterator should be used to * avoid having huge array lists in memory. * * @author olli */ public abstract class Directive { public static final String DEFAULT_NS="http://wandora.org/si/query/"; public static final String DEFAULT_COL="#DEFAULT"; public static Addon[] getStandardAddonHints(){ return getStandardAddonHints(new Addon[0]); } public static Addon[] getStandardAddonHints(Addon[] extras){ ArrayList<Addon> addons=new ArrayList<Addon>(); addons.add(new Addon("as", new Parameter[]{new Parameter(String.class,false,"column name")}, "as")); addons.add(new Addon("as", new Parameter[]{ new Parameter(String.class,false,"old column name"), new Parameter(String.class,false,"new column name") }, "as")); addons.add(new Addon("from", new Parameter[]{new Parameter(String.class,true,"literal")}, "from literals")); addons.add(new Addon("of", new Parameter[]{new Parameter(String.class,false,"column")}, "of")); addons.add(new Addon("where", new Parameter[]{new Parameter(Directive.class,false,"where directive")}, "where")); addons.add(new Addon("where", new Parameter[]{ new Parameter(Operand.class,Object.class,false,"operand 1"), new Parameter(String.class,false,"operator"), new Parameter(Operand.class,Object.class,false,"operand 2") }, "where")); addons.add(new Addon("where", new Parameter[]{ new Parameter(TopicOperand.class,Object.class,false,"topic operand 1"), new Parameter(String.class,false,"operator"), new Parameter(TopicOperand.class,Object.class,false,"topic operand 2") }, "where")); if(extras!=null && extras.length>0) { for(int i=0;i<extras.length;i++) { addons.add(extras[i]); } } return addons.toArray(new Addon[addons.size()]); } /** * Prepares the query for execution. Extending classes must propagate * the call to any contained queries. */ public boolean startQuery(QueryContext context) throws QueryException { return true; } /** * Signals end of query and performs any cleanup that may be needed. * Extending classes must propagate the call to any contained queries. */ public void endQuery(QueryContext context) throws QueryException { } /** * Executes the query buffering all results in a list and returning that. * This may be useful at the top level where the results are going to be * retrieved entirely in a list anyway. Inside the query you should avoid * using this as the intermediate results can become very large due to * join operations. * * startQuery must have been called before calling this and endQuery after * the query is done. If this is the top level directive you may have to do * it manually. These call should propaget automaticall to all inner queries. */ public ArrayList<ResultRow> query(QueryContext context,ResultRow input) throws QueryException { ResultIterator iter=queryIterator(context,input); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); while(iter.hasNext()) { if(context.checkInterrupt()) throw new QueryException("Execution interrupted"); res.add(iter.next()); } iter.dispose(); return res; } /** * This method does all necessary preparations, executes the query and * returns with a list containing the results. This is the easiest way * to execute a query. You can interrupt the query through the context * object by calling interrupt in it. */ public ArrayList<ResultRow> doQuery(QueryContext context,ResultRow input) throws QueryException { if(!startQuery(context)) return new ArrayList<ResultRow>(); ArrayList<ResultRow> ret=query(context,input); endQuery(context); return ret; } /** * You must call startQuery before calling this and endQuery after you are * done with the result iterator. You should also call dispose of the * result iterator when you're done. */ public ResultIterator queryIterator(QueryContext context,ResultRow input) throws QueryException { return new ResultIterator.ListIterator(query(context,input)); } public Directive join(Directive directive){ return new Join(this,directive); } public Directive to(Directive[] directives){ Directive to=null; for(int i=0;i<directives.length;i++){ if(to==null) to=directives[i]; else to=to.join(directives[i]); } return new From(to,this); } public Directive to(Directive d1){return to(new Directive[]{d1});} public Directive to(Directive d1,Directive d2){return to(new Directive[]{d1,d2});} public Directive to(Directive d1,Directive d2,Directive d3){return to(new Directive[]{d1,d2,d3});} public Directive to(Directive d1,Directive d2,Directive d3,Directive d4){return to(new Directive[]{d1,d2,d3,d4});} public Directive from(Directive[] directives){ Directive from=null; for(int i=0;i<directives.length;i++){ if(from==null) from=directives[i]; else from=from.join(directives[i]); } return new From(this,from); } public Directive from(Directive d1){return from(new Directive[]{d1});} public Directive from(Directive d1,Directive d2){return from(new Directive[]{d1,d2});} public Directive from(Directive d1,Directive d2,Directive d3){return from(new Directive[]{d1,d2,d3});} public Directive from(Directive d1,Directive d2,Directive d3,Directive d4){return from(new Directive[]{d1,d2,d3,d4});} public Directive from(String[] literals){ return from(new Literals(literals)); } public Directive from(String s1){return from(new String[]{s1});} public Directive from(String s1,String s2){return from(new String[]{s1,s2});} public Directive from(String s1,String s2,String s3){return from(new String[]{s1,s2,s3});} public Directive from(String s1,String s2,String s3,String s4){return from(new String[]{s1,s2,s3,s4});} public Directive of(String col){ return this.from(new Of(col)); } public Directive where(Object c1,String comp,Object c2){ return where(new Compare(c1,comp,c2)); } public Directive where(Directive d){ return d.from(this); } public Directive as(String newRole){ return new As(newRole).from(this); } public Directive as(String original,String newRole){ return new As(original,newRole).from(this); } public boolean isStatic(){ return false; } public static String debugStringInner(Directive[] directives,String indent){ StringBuilder ret=new StringBuilder(""); if(directives==null){ ret.append("null"); } else { ret.append("\n"); for(int i=0;i<directives.length;i++){ if(i>0) ret.append(",\n"); ret.append(indent+"\t"); ret.append(directives[i].debugString(indent+"\t")); } ret.append("\n"); } ret.append(indent); return ret.toString(); } public static String debugStringInner(List<Directive> directives,String indent){ StringBuilder ret=new StringBuilder("\n"); for(int i=0;i<directives.size();i++){ if(i>0) ret.append(",\n"); ret.append(indent+"\t"); ret.append(directives.get(i).debugString(indent+"\t")); } ret.append("\n"); ret.append(indent); return ret.toString(); } public static String debugStringInner(Directive directive,String indent){ StringBuilder sb=new StringBuilder(""); sb.append("\n\t"+indent); if(directive==null) sb.append("null"); else sb.append(directive.debugString(indent+"\t")); sb.append("\n"+indent); return sb.toString(); } public String debugStringParams(){return "";} public String debugStringParams(String indent){return debugStringParams();} public String debugString(){ return debugString(""); } public String debugString(String indent){ return this.getClass().getSimpleName()+"("+debugStringParams(indent)+")"; } /* public static String getOperandString(Object o,QueryContext context,ResultRow input) throws QueryException { Object ob=getOperand(o,context,input); if(ob==null) return null; else return ob.toString(); } public static Object getOperand(Object o,QueryContext context,ResultRow input) throws QueryException { if(o==null) return null; else if(o instanceof Directive) { ResultIterator iter=((Directive)o).queryIterator(context, input); if(iter.hasNext()){ Object ret=iter.next().getActiveValue(); iter.dispose(); return ret; } else { return null; } } else return o; } */ public static void main(String[] args) throws Exception { /* String debug= new BaseName().of("#in").as("#bn").from( new Instances().from("http://wandora.org/si/core/schema-type").as("#in"), new Literals("Content type").as("#literals") ).where("#bn","=","#literals").debugString();*/ /* String debug= new Players("http://www.wandora.net/freedb/track", "http://www.wandora.net/freedb/artist" ).as("#artist").of("#track").from( new Regex("^([^\\(]*).*$","$1",0).from( new BaseName().from( new Instances().from("http://www.wandora.net/freedb/track") .as("#track") ) ).as("#trackname"), new Regex("^([^\\(]*).*$","$1",0).from( new BaseName().from( new Players( "http://www.wandora.net/freedb/track", "http://www.wandora.net/freedb/track" ).as("#queentrack").from( new Literals("http://www.wandora.net/freedb/artist/QUEEN").as("#queen") ) ) ).as("#queenname") ).where("#trackname","=","#queenname") .where("#artist","t!=","#queen").debugString();*/ String debug=new Identity().as("#b").of("#c").from(new BaseName()).debugString(); System.out.println(debug); debug=new Identity().of("#c").as("#b").from(new BaseName()).debugString(); System.out.println(debug); debug=new Identity().of("#c").from(new BaseName()).as("#b").debugString(); System.out.println(debug); } }
12,247
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ResultIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/ResultIterator.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ResultIterator.java * * */ package org.wandora.query2; import java.util.ArrayList; import java.util.NoSuchElementException; /** * * @author olli */ public abstract class ResultIterator { /** * Gets the next row in the results and moves the iterator forward one row. * If there are no more rows NoSuchElementException is thrown. */ public abstract ResultRow next() throws QueryException, NoSuchElementException; /** * Checks if there is another row available. */ public abstract boolean hasNext() throws QueryException; /** * Finalizes the iterator and performs any cleanup needed. This iterator * cannot be used at all after a call to this. */ public abstract void dispose() throws QueryException; /** * Resets the iterator to its initial position. */ public abstract void reset() throws QueryException; public static class ListIterator extends ResultIterator { public int pointer; public ArrayList<ResultRow> res; public ListIterator(ArrayList<ResultRow> res){ this.res=res; pointer=0; } public boolean hasNext(){ return pointer<res.size(); } public ResultRow next() throws NoSuchElementException { if(pointer>=res.size()) throw new NoSuchElementException(); return res.get(pointer++); } public void dispose(){ } public void reset(){ pointer=0; } } public static class CachedIterator extends ResultIterator { public ArrayList<ResultRow> cache; public int maxCacheSize=1000; public ResultIterator iter; public int pointer=-1; public CachedIterator(ResultIterator iter){ cache=new ArrayList<ResultRow>(); this.iter=iter; } public boolean hasNext() throws QueryException { if(pointer>=0){ return pointer<cache.size(); } else { if(iter.hasNext()) return true; else { if(cache!=null) pointer=cache.size(); // pointer>=0 marks cache usable return false; } } } public ResultRow next() throws QueryException, NoSuchElementException { if(pointer>=0){ if(pointer>=cache.size()) throw new NoSuchElementException(); return cache.get(pointer++); } else{ if(iter.hasNext()){ ResultRow row=iter.next(); if(cache!=null){ if(cache.size()<maxCacheSize) { cache.add(row); } else { cache=null; // don't try to use cache from now on } } return row; } else throw new NoSuchElementException(); } } public void dispose() throws QueryException { if(cache!=null) cache=null; iter.dispose(); } public void reset() throws QueryException { if(pointer>=0) { pointer=0; } else { if(cache!=null) cache=new ArrayList<ResultRow>(); iter.reset(); } } } public static class BufferedIterator extends ResultIterator { public ResultIterator iter; public ArrayList<ResultRow> buffer; public int pointer; public int bufferSize=5000; public BufferedIterator(ResultIterator iter){ this.iter=iter; pointer=0; } private boolean fillBuffer() throws QueryException { if(buffer!=null) buffer.clear(); else buffer=new ArrayList<ResultRow>(bufferSize/4); while(iter.hasNext() && buffer.size()<bufferSize){ buffer.add(iter.next()); } pointer=0; if(buffer.size()>0) return true; else return false; } public boolean hasNext() throws QueryException { if(buffer==null || pointer>=buffer.size()) { return fillBuffer(); } return true; } public ResultRow next() throws QueryException, NoSuchElementException { if(!hasNext()) throw new NoSuchElementException(); return buffer.get(pointer++); } public void dispose() throws QueryException { buffer=null; iter.dispose(); } public void reset() throws QueryException { buffer=null; pointer=0; iter.reset(); } } public static class EmptyIterator extends ResultIterator { public EmptyIterator(){} public boolean hasNext(){ return false; } public ResultRow next() throws NoSuchElementException { throw new NoSuchElementException(); } public void dispose(){} public void reset(){} } public static class SingleIterator extends ResultIterator { public ResultRow row; public boolean returned; public SingleIterator(ResultRow row){ this.row=row; this.returned=false; } public boolean hasNext(){ return !returned; } public ResultRow next() throws NoSuchElementException { if(!returned) { returned=true; return row; } else throw new NoSuchElementException(); } public void dispose(){} public void reset(){ returned=false; } } }
6,659
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Join.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Join.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Join.java * */ package org.wandora.query2; import java.util.ArrayList; import java.util.NoSuchElementException; /** * * @author olli */ public class Join extends Directive implements DirectiveUIHints.Provider { private ArrayList<Directive> directives; public Join(){} public Join(Directive[] directives){ this.directives=new ArrayList<Directive>(); for(int i=0;i<directives.length;i++){ this.directives.add(directives[i]); } } public Join(Directive d1,Directive d2){ this(new Directive[]{d1,d2}); } public Join(Directive d1,Directive d2,Directive d3){ this(new Directive[]{d1,d2,d3}); } public Join(Directive d1,Directive d2,Directive d3,Directive d4){ this(new Directive[]{d1,d2,d3,d4}); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Join.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, true, "directives"), }, ""), }, Directive.getStandardAddonHints(), "Join", "Framework"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { boolean r=true; for(Directive d : directives){ r&=d.startQuery(context); } return r; } @Override public void endQuery(QueryContext context) throws QueryException { for(Directive d : directives){ d.endQuery(context); } } @Override public Directive join(Directive directive){ this.directives.add(directive); return this; } /* @Override public ArrayList<ResultRow> query(QueryContext context,ResultRow input,String as) throws QueryException { ArrayList<ArrayList<ResultRow>> res=new ArrayList<ArrayList<ResultRow>>(); for(Directive d: directives){ ArrayList<ResultRow> r=d.query(context,input,null); res.add(r); } ArrayList<ResultRow> ret=new ArrayList<ResultRow>(); int[] pointers=new int[res.size()]; for(int i=0;i<pointers.length;i++) pointers[i]=0; Outer: while(true){ ResultRow row=null; for(int i=0;i<pointers.length;i++){ if(i==0) row=res.get(0).get(pointers[0]); else{ row=row.join(res.get(i).get(pointers[i])); } } ret.add(row); for(int i=pointers.length-1;i>=-1;i--){ if(i==-1){ break Outer; } pointers[i]++; if(pointers[i]>=res.get(i).size()){ pointers[i]=0; continue; } else break; } } return ret; } */ @Override public ResultIterator queryIterator(QueryContext context,ResultRow input) throws QueryException { return new JoinIterator(context,input); } @Override public boolean isStatic(){ for(Directive d : directives){ if(!d.isStatic()) return false; } return true; } public String debugStringParams(String indent){ return debugStringInner(directives,indent); } private class JoinIterator extends ResultIterator { public QueryContext context; public ResultRow input; public ArrayList<ResultIterator> iterators; public boolean allDone=false; public ResultRow nextRow; public ResultRow[] rows; public int counter=0; public long startTime=0; public JoinIterator(QueryContext context,ResultRow input) throws QueryException { this.context=context; this.input=input; iterators=new ArrayList<ResultIterator>(); for(int i=0;i<directives.size();i++){ ResultIterator iter=directives.get(i).queryIterator(context,input); if(i>0 && !(iter instanceof ResultIterator.EmptyIterator) && !(iter instanceof ResultIterator.SingleIterator) && !(iter instanceof ResultIterator.ListIterator) && !(iter instanceof ResultIterator.CachedIterator) ) iter=new ResultIterator.CachedIterator(iter); iterators.add(iter); } rows=new ResultRow[iterators.size()]; for(int i=0;i<rows.length;i++){ if(!iterators.get(i).hasNext()){ allDone=true; break; } else rows[i]=iterators.get(i).next(); } nextRow=null; } public boolean hasNext() throws QueryException { if(nextRow!=null) return true; if(allDone) return false; if(context.checkInterrupt()) throw new QueryException("Execution interrupted"); // if(counter==0) startTime=System.currentTimeMillis(); ResultRow row=null; for(int i=0;i<rows.length;i++){ if(row==null){ row=rows[i]; } else if(rows[i]!=null) { row=row.join(rows[i]); } } if(row==null) return false; nextRow=row; // counter++; // if((counter%50000)==0){ // double speed=50000.0/(double)(System.currentTimeMillis()-startTime)*1000.0; // System.out.println("Join counter "+counter+" "+speed); // startTime=System.currentTimeMillis(); // } for(int i=iterators.size()-1;i>=0;i--){ ResultIterator iter=iterators.get(i); if(iter.hasNext()){ rows[i]=iter.next(); break; } else{ if(i==0){ allDone=true; break; } else{ iter.reset(); rows[i]=null; if(iter.hasNext()) rows[i]=iter.next(); continue; } } } return true; } public ResultRow next() throws QueryException,NoSuchElementException { if(hasNext()){ ResultRow temp=nextRow; nextRow=null; return temp; } else throw new NoSuchElementException(); } public void dispose() throws QueryException { for(ResultIterator iter : iterators){ iter.dispose(); } } public void reset() throws QueryException { for(ResultIterator iter : iterators){ iter.reset(); } rows=new ResultRow[iterators.size()]; for(int i=0;i<rows.length;i++){ if(!iterators.get(i).hasNext()) rows[i]=null; else rows[i]=iterators.get(i).next(); } nextRow=null; allDone=false; } } }
8,242
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Sum.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Sum.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Sum.java * */ package org.wandora.query2; /** * * @author olli */ public class Sum extends Directive implements DirectiveUIHints.Provider { private Directive directive; private boolean asDouble; public Sum(){} public Sum(Directive directive,boolean asDouble){ this.directive=directive; this.asDouble=asDouble; } public Sum(Directive directive){ this(directive,false); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Sum.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive"), new DirectiveUIHints.Parameter(Boolean.class, false, "asDouble") }, "") }, Directive.getStandardAddonHints(), "Sum", "Aggregate"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); double sum=0.0; while(iter.hasNext()) { ResultRow row=iter.next(); Object v=row.getActiveValue(); if(v==null) continue; double d=Double.parseDouble(v.toString()); sum+=d; } String val; if(asDouble) val=""+sum; else val=""+(int)sum; return input.addValue(DEFAULT_COL, val).toIterator(); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
3,008
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Null.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Null.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Null.java * * */ package org.wandora.query2; /** * * @author olli */ public class Null extends Directive implements DirectiveUIHints.Provider { public Null(){ } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Null.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, "") }, Directive.getStandardAddonHints(), "Null", "Primitive"); return ret; } @Override public boolean isStatic() { return true; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { return new ResultRow(null).toIterator(); } }
1,617
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicOperand.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/TopicOperand.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * TopicOperand.java * */ package org.wandora.query2; import static org.wandora.utils.Tuples.t2; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class TopicOperand extends Operand { public T2<Topic,String> cachedTopic; public boolean topicIsCached=false; public TopicOperand(){} public TopicOperand(Object operand){ super(operand); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Players.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Object.class, false, "operand"), }, "") }, Directive.getStandardAddonHints(), "TopicOperand", "Framework"); return ret; } public static TopicOperand makeTopicOperand(Object o){ if(o!=null && o instanceof TopicOperand) return (TopicOperand)o; else if(o!=null && o instanceof Operand) return new TopicOperand(((Operand)o).operand); else return new TopicOperand(o); } public static TopicOperand[] makeTopicOperands(Object[] os){ TopicOperand[] ret=new TopicOperand[os.length]; for(int i=0;i<ret.length;i++){ ret[i]=makeTopicOperand(os[i]); } return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { topicIsCached=false; cachedTopic=null; return super.startQuery(context); } public T2<Topic,String> getOperandTopicAndSI(QueryContext context, ResultRow input) throws QueryException { if(stat && topicIsCached) return cachedTopic; Object o=getOperandObject(context, input); T2<Topic,String> ret=null; try{ if(o==null) { ret=t2(null,null); } else if(o instanceof Topic){ ret=t2((Topic)o,((Topic)o).getOneSubjectIdentifier().toExternalForm()); } else { Topic t=context.getTopicMap().getTopic(o.toString()); ret=t2(t,o.toString()); } if(stat){ cachedTopic=ret; topicIsCached=true; } return ret; } catch(TopicMapException tme){ throw new QueryException(tme); } } public Topic getOperandTopic(QueryContext context, ResultRow input) throws QueryException { return getOperandTopicAndSI(context, input).e1; } public String getOperandSI(QueryContext context,ResultRow input) throws QueryException { return getOperandTopicAndSI(context, input).e2; } }
3,672
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Average.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Average.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Average.java * */ package org.wandora.query2; /** * * @author olli */ public class Average extends Directive implements DirectiveUIHints.Provider { private Directive directive; public Average(){} public Average(Directive directive){ this.directive=directive; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Average.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, "") }, Directive.getStandardAddonHints(), "Average", "Aggregate"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); double sum=0.0; int count=0; while(iter.hasNext()) { ResultRow row=iter.next(); Object v=row.getActiveValue(); count++; if(v==null) continue; double d=Double.parseDouble(v.toString()); sum+=d; } String val=""+(sum/count); return input.addValue(DEFAULT_COL, val).toIterator(); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
2,590
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Roles.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Roles.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Roles.java * * */ package org.wandora.query2; import java.util.ArrayList; /** * * @author olli */ public class Roles extends Directive implements DirectiveUIHints.Provider { private String[] roles; private boolean not; public Roles(){this(new String[0]);} public Roles(String[] roles){ this(roles,false); } public Roles(String[] roles,boolean not){ this.roles=roles; this.not=not; } public Roles(String s1){this(new String[]{s1});} public Roles(String s1,String s2){this(new String[]{s1,s2});} public Roles(String s1,String s2,String s3){this(new String[]{s1,s2,s3});} public Roles(String s1,String s2,String s3,String s4){this(new String[]{s1,s2,s3,s4});} public Roles(String s1,boolean not){this(new String[]{s1},not);} public Roles(String s1,String s2,boolean not){this(new String[]{s1,s2},not);} public Roles(String s1,String s2,String s3,boolean not){this(new String[]{s1,s2,s3},not);} public Roles(String s1,String s2,String s3,String s4,boolean not){this(new String[]{s1,s2,s3,s4},not);} @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Roles.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, true, "roles") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, true, "roles"), new DirectiveUIHints.Parameter(Boolean.class, false, "not") }, "") }, Directive.getStandardAddonHints(), "Roles", "Structure"); return ret; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ArrayList<String> newRoles=new ArrayList<String>(); ArrayList<Object> newValues=new ArrayList<Object>(); int active=0; if(not==false){ for(int i=0;i<roles.length;i++){ Object value=null; for(int j=0;j<input.getNumValues();j++){ if(input.getRole(j).equals(roles[i])){ value=input.getValue(j); if(input.getActiveColumn()==j) active=i; break; } } newRoles.add(roles[i]); newValues.add(value); } } else{ Outer: for(int j=0;j<input.getNumValues();j++){ String inRole=input.getRole(j); for(int i=0;i<roles.length;i++){ if(inRole.equals(roles[i])) { continue Outer; } } newRoles.add(inRole); newValues.add(input.getValue(j)); } } return new ResultRow(newRoles,newValues,active,true).toIterator(); } }
3,926
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OrderBy.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/OrderBy.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * OrderBy.java * */ package org.wandora.query2; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * * @author olli */ public class OrderBy extends Directive implements DirectiveUIHints.Provider { private Comparator<Object> comparator; private Directive directive; public OrderBy(){ this(new Identity()); } public OrderBy(Directive directive){ this(directive,new Comparator<Object>(){ public int compare(Object v1, Object v2) { if(v1==null){ if(v2==null) return 0; else return -1; } else if(v2==null) return 1; else return v1.toString().compareTo(v2.toString()); } }); } public OrderBy(Directive directive,Comparator<Object> comparator){ this.directive=directive; this.comparator=comparator; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(OrderBy.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), /* // comparator type not supported by ui new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive"), new DirectiveUIHints.Parameter(Comparator.class, false, "comparator") }, ""),*/ }, Directive.getStandardAddonHints(), "OrderBy", "Structure"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ArrayList<ResultRow> res=directive.query(context, input); Collections.sort(res, new Comparator<ResultRow>(){ public int compare(ResultRow o1, ResultRow o2) { Object v1=o1.getActiveValue(); Object v2=o2.getActiveValue(); return comparator.compare(v1, v2); } }); return new ResultIterator.ListIterator(res); } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } }
3,678
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Operand.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Operand.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Operand.java * */ package org.wandora.query2; /** * * @author olli */ public class Operand extends Directive implements DirectiveUIHints.Provider { protected Object operand; protected boolean stat; protected Object cache; protected boolean isCached; public Operand(){} public Operand(Object operand){ this.operand=operand; if(operand!=null && operand instanceof Directive){ stat=((Directive)operand).isStatic(); } else stat=true; } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Players.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Object.class, false, "operand"), }, "") }, Directive.getStandardAddonHints(), "Operand", "Framework"); return ret; } public static Operand makeOperand(Object o){ if(o!=null && o instanceof Operand) return (Operand)o; else return new Operand(o); } public static Operand[] makeOperands(Object[] os){ Operand[] ret=new Operand[os.length]; for(int i=0;i<ret.length;i++){ ret[i]=makeOperand(os[i]); } return ret; } public static boolean startOperands(QueryContext context,Operand ... os) throws QueryException{ boolean ret=true; for(int i=0;i<os.length;i++){ ret&=os[i].startQuery(context); } return ret; } public static void endOperands(QueryContext context,Operand ... os) throws QueryException { for(int i=0;i<os.length;i++){ os[i].endQuery(context); } } @Override public boolean startQuery(QueryContext context) throws QueryException { isCached=false; cache=null; if(operand!=null && operand instanceof Directive){ return ((Directive)operand).startQuery(context); } else return true; } @Override public void endQuery(QueryContext context) throws QueryException { if(operand!=null && operand instanceof Directive){ ((Directive)operand).endQuery(context); } } @Override public boolean isStatic() { return stat; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { // This isn't usually used for operand directives. getOperandObejct is used instead. return new ResultRow(getOperandObject(context,input)).toIterator(); } public String getOperandString(QueryContext context,ResultRow input) throws QueryException { Object ret=getOperandObject(context,input); if(ret==null) return null; else return ret.toString(); } public Object getOperandObject(QueryContext context,ResultRow input) throws QueryException { if(stat && isCached) return cache; Object ret=null; if(operand==null) ret=null; else if(operand.getClass()==Of.class){ // Special handling for one common case. Skips the creation of ResultIterators and such. ret=input.getValue(((Of)operand).getRole()); } else if(operand instanceof Directive) { ResultIterator iter=((Directive)operand).queryIterator(context, input); if(iter.hasNext()){ ret=iter.next().getActiveValue(); } else { ret=null; } iter.dispose(); } else ret=operand; if(stat){ isCached=true; cache=ret; } return ret; } }
4,603
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Empty.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Empty.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Empty.java * * */ package org.wandora.query2; /** * * @author olli */ public class Empty extends Directive implements DirectiveUIHints.Provider { public Empty(){} @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Empty.class,new DirectiveUIHints.Constructor[]{ }, Directive.getStandardAddonHints(), "Empty", "Primitive"); return ret; } @Override public boolean isStatic() { return true; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { return new ResultIterator.EmptyIterator(); } }
1,529
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Literals.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Literals.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Literals.java * * */ package org.wandora.query2; import java.util.ArrayList; /** * * @author olli */ public class Literals extends Directive implements DirectiveUIHints.Provider { private ArrayList<ResultRow> result; public Literals(){ result=new ArrayList<ResultRow>(); } public Literals(String[] strings) { result=new ArrayList<ResultRow>(); for(int i=0;i<strings.length;i++){ ResultRow r=new ResultRow(strings[i]); result.add(r); } } public Literals(String s1){this(new String[]{s1});} public Literals(String s1,String s2){this(new String[]{s1,s2});} public Literals(String s1,String s2,String s3){this(new String[]{s1,s2,s3});} public Literals(String s1,String s2,String s3,String s4){this(new String[]{s1,s2,s3,s4});} @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Literals.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(String.class, true, "value") }, "") }, Directive.getStandardAddonHints(), "Literals", "Primitive"); return ret; } @Override public ArrayList<ResultRow> query(QueryContext context, ResultRow input) throws QueryException { return result; } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { if(result.size()==1) return result.get(0).toIterator(); else return super.queryIterator(context, input); } @Override public boolean isStatic(){ return true; } @Override public String debugStringParams(){ StringBuffer ret=new StringBuffer(); for(int i=0;i<result.size();i++){ if(i>0) ret.append(","); ret.append("\""+result.get(i).getActiveValue()+"\""); } return ret.toString(); } }
2,886
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Compare.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Compare.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Compare.java * */ package org.wandora.query2; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class Compare extends WhereDirective implements DirectiveUIHints.Provider { public static final int EQ=0; public static final int NE=1; public static final int LT=2; public static final int GT=3; public static final int LE=4; public static final int GE=5; public static final int OP_MASK=0xFF; public static final int TYPE_MASK=0xFF00; public static final int TYPE_STRING=0; public static final int TYPE_NUMERIC=256; public static final int TYPE_TOPIC=512; private Operand operand1; private Operand operand2; private int operator; public Compare(){} public Compare(Object operand1,int operator,Object operand2){ if( (operator&TYPE_MASK)==TYPE_TOPIC ) { this.operand1=TopicOperand.makeTopicOperand(operand1); this.operand2=TopicOperand.makeTopicOperand(operand2); } else { this.operand1=Operand.makeOperand(operand1); this.operand2=Operand.makeOperand(operand2); } this.operator=operator; } public Compare(Object operand1,String operator,Object operand2){ this(operand1,parseOperator(operator),operand2); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Compare.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Operand.class, false, "operand 1"), new DirectiveUIHints.Parameter(String.class, false, "operator"), new DirectiveUIHints.Parameter(Operand.class, false, "operand 2") }, "") }, Directive.getStandardAddonHints(), "Compare", "Where directive"); return ret; } public static int parseOperator(String operator){ int mode=0; operator=operator.toLowerCase(); if(operator.startsWith("n")) { mode=TYPE_NUMERIC; operator=operator.substring(1); } else if(operator.startsWith("t")) { mode=TYPE_TOPIC; operator=operator.substring(1); } else if(operator.startsWith("s")) { mode=TYPE_STRING; operator=operator.substring(1); } if(operator.equals("=") || operator.equals("==")) return mode|EQ; else if(operator.equals("!=") || operator.equals("<>") || operator.equals("~=")) return mode|NE; else if(operator.equals("<")) return mode|LT; else if(operator.equals(">")) return mode|GT; else if(operator.equals("<=")) return mode|LE; else if(operator.equals(">=")) return mode|GE; else return EQ; } @Override public void endQuery(QueryContext context) throws QueryException { operand1.endQuery(context); operand2.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { return operand1.startQuery(context) & operand2.startQuery(context); } @Override public boolean includeRow(QueryContext context,ResultRow row) throws QueryException { int mode=(operator&TYPE_MASK); Object v1=null; Object v2=null; TopicMap tm=context.getTopicMap(); int compare=0; boolean cond=false; if(v1==null || v2==null) cond=true; if(mode==TYPE_NUMERIC){ v1=operand1.getOperandObject(context, row); v2=operand2.getOperandObject(context, row); if(v1!=null) { try{ v1=Double.parseDouble(v1.toString()); }catch(NumberFormatException nfe){v1=null;} } if(v2!=null) { try{ v2=Double.parseDouble(v2.toString()); }catch(NumberFormatException nfe){v2=null;} } if(v1==null && v2==null) compare=0; else if(v1==null && v2!=null) compare=-1; else if(v1!=null && v2==null) compare=1; else compare=Double.compare((Double)v1, (Double)v2); } else if(mode==TYPE_TOPIC){ Topic t1=((TopicOperand)operand1).getOperandTopic(context, row); Topic t2=((TopicOperand)operand2).getOperandTopic(context, row); try{ if(t1==null || t2==null) compare=-1; else if(t1.mergesWithTopic(t2)) compare=0; else compare=1; }catch(TopicMapException tme){ throw new QueryException(tme); } } else { v1=operand1.getOperandObject(context, row); v2=operand2.getOperandObject(context, row); if(v1==null && v2==null) compare=0; else if(v1==null && v2!=null) compare=-1; else if(v1!=null && v2==null) compare=1; else compare=v1.toString().compareTo(v2.toString()); } switch(operator&OP_MASK){ case EQ: if(compare==0) return true; break; case NE: if(compare!=0) return true; break; case LT: if(compare<0) return true; break; case GT: if(compare>0) return true; break; case LE: if(compare<=0) return true; break; case GE: if(compare>=0) return true; break; } return false; } }
6,529
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
First.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/First.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * First.java * * */ package org.wandora.query2; import java.util.NoSuchElementException; /** * * @author olli */ public class First extends Directive implements DirectiveUIHints.Provider { private Directive directive; private int count; public First(){} public First(int count,Directive directive){ this.directive=directive; this.count=count; } public First(Directive directive){ this(1,directive); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(First.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Integer.class, false, "count"), new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, "") }, Directive.getStandardAddonHints(), "First", "Structure"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return directive.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { directive.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { ResultIterator iter=directive.queryIterator(context, input); if(!iter.hasNext() || count==0) return new ResultIterator.EmptyIterator(); else { if(count==1) { ResultIterator ret=iter.next().toIterator(); iter.dispose(); return ret; } else { return new FirstIterator(count,iter); } } } @Override public String debugStringParams(String indent) { return debugStringInner(directive,indent); } private class FirstIterator extends ResultIterator { public int counter; public int count; public ResultIterator iter; public FirstIterator(int count,ResultIterator iter) throws QueryException { this.count=count; this.iter=iter; counter=0; } @Override public void dispose() throws QueryException { iter.dispose(); } @Override public boolean hasNext() throws QueryException { if(counter<count && this.iter.hasNext()) return true; else return false; } @Override public ResultRow next() throws QueryException, NoSuchElementException { if(hasNext()){ counter++; return iter.next(); } else throw new NoSuchElementException(); } @Override public void reset() throws QueryException { counter=0; iter.reset(); } } }
4,023
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IsOfType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/IsOfType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * IsOfType.java * * */ package org.wandora.query2; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class IsOfType extends WhereDirective implements DirectiveUIHints.Provider { private TopicOperand topicOp; public IsOfType(){}; public IsOfType(Object o){ this.topicOp=new TopicOperand(o); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(IsOfType.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(TopicOperand.class, false, "operand") }, "") }, Directive.getStandardAddonHints(), "IsOfType", "Where directive"); return ret; } @Override public void endQuery(QueryContext context) throws QueryException { topicOp.endQuery(context); } @Override public boolean startQuery(QueryContext context) throws QueryException { return topicOp.startQuery(context); } @Override public boolean includeRow(QueryContext context, ResultRow input) throws QueryException { Object o=input.getActiveValue(); if(o==null) return false; try{ if(!(o instanceof Topic)){ o=context.getTopicMap().getTopic(o.toString()); if(o==null) return false; } Topic type=topicOp.getOperandTopic(context, input); if(type==null) return false; Topic t=(Topic)o; if(t.isOfType(type)) return true; else return false; }catch(TopicMapException tme){ throw new QueryException(tme); } } }
2,639
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Recursive.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/query2/Recursive.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Recursive.java * */ package org.wandora.query2; import java.util.HashSet; import java.util.LinkedList; import java.util.NoSuchElementException; /** * * @author olli */ public class Recursive extends Directive implements DirectiveUIHints.Provider { private Directive recursion; private int maxDepth; private boolean onlyLeaves; public Recursive(){} public Recursive(Directive recursion, int maxDepth, boolean onlyLeaves){ this.recursion=recursion; this.maxDepth=maxDepth; this.onlyLeaves=onlyLeaves; } public Recursive(Directive recursion, int maxDepth){ this(recursion,maxDepth,false); } public Recursive(Directive recursion){ this(recursion,-1,false); } @Override public DirectiveUIHints getUIHints() { DirectiveUIHints ret=new DirectiveUIHints(Recursive.class,new DirectiveUIHints.Constructor[]{ new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive"), new DirectiveUIHints.Parameter(Integer.class, false, "maxDepth") }, ""), new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{ new DirectiveUIHints.Parameter(Directive.class, false, "directive"), new DirectiveUIHints.Parameter(Integer.class, false, "maxDepth"), new DirectiveUIHints.Parameter(Boolean.class, false, "onlyLeaves"), }, "") }, Directive.getStandardAddonHints(), "Recursive", "Structure"); return ret; } @Override public boolean startQuery(QueryContext context) throws QueryException { return recursion.startQuery(context); } @Override public void endQuery(QueryContext context) throws QueryException { recursion.endQuery(context); } @Override public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException { return new RecursionIterator(context,input); } @Override public String debugStringParams(String indent) { return debugStringInner(recursion,indent); } private class RecursionIterator extends ResultIterator { public QueryContext context; public ResultRow input; public ResultIterator iter; public HashSet<Object> processed; public LinkedList<ResultIterator> queue; public LinkedList<ResultIterator> nextQueue; public int depth; public ResultRow nextRow; public RecursionIterator(QueryContext context, ResultRow input) throws QueryException { this.context=context; this.input=input; reset(); } @Override public void dispose() throws QueryException { if(iter!=null) iter.dispose(); if(queue!=null){ for(ResultIterator ri : queue){ ri.dispose(); } } if(nextQueue!=null){ for(ResultIterator ri : nextQueue){ ri.dispose(); } } } @Override public boolean hasNext() throws QueryException { if(nextRow!=null) return true; if(maxDepth!=-1 && depth>maxDepth) return false; while(true){ while(!iter.hasNext()){ iter.dispose(); if(queue.isEmpty()){ queue=nextQueue; nextQueue=new LinkedList<ResultIterator>(); depth++; if(maxDepth!=-1 && depth>maxDepth) return false; if(queue.isEmpty()) return false; } iter=queue.removeFirst(); } nextRow=iter.next(); Object val=nextRow.getActiveValue(); if(processed.add(val)){ ResultIterator newIter=recursion.queryIterator(context, input.addValue(input.getActiveRole(), val)); if(newIter.hasNext()) nextQueue.add(newIter); if(onlyLeaves && newIter.hasNext()){ nextRow=null; } else return true; } } } @Override public ResultRow next() throws QueryException, NoSuchElementException { if(hasNext()){ ResultRow ret=nextRow; nextRow=null; return ret; } else throw new NoSuchElementException(); } @Override public void reset() throws QueryException { dispose(); processed=new HashSet<Object>(); queue=new LinkedList<ResultIterator>(); nextQueue=new LinkedList<ResultIterator>(); iter=recursion.queryIterator(context, input); nextRow=null; depth=0; } } }
6,138
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DataURL.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/DataURL.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.awt.Image; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.util.Arrays; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.wandora.application.gui.UIBox; /** * * @author akivela */ public class DataURL { public static String defaultStringEncoding = "utf-8"; private byte[] data = new byte[] { }; private String encoding = "base64"; private String mimetype = "application/octet-stream"; public DataURL() { } public DataURL(String dataUrl) throws MalformedURLException { parseDataURL(dataUrl); } public DataURL(File file) throws MalformedURLException { if(file != null) { mimetype = MimeTypes.getMimeType(file); setData(file); } else { throw new MalformedURLException(); } } public DataURL(URL url) throws MalformedURLException { if(url != null) { mimetype = MimeTypes.getMimeType(url); setData(url); } else { throw new MalformedURLException(); } } public DataURL(Image image) throws MalformedURLException { File tempFile = null; try { if(image != null) { String prefix = "wandora" + image.hashCode(); String suffix = ".png"; tempFile = File.createTempFile(prefix, suffix); tempFile.deleteOnExit(); ImageIO.write(UIBox.makeBufferedImage(image), "png", tempFile); mimetype = MimeTypes.getMimeType("png"); setData(Files.readAllBytes(tempFile.toPath())); } } catch(Exception e) { e.printStackTrace(); } } public DataURL(byte[] data) { this.data = data; } public DataURL(String mimetype, byte[] data) { this.mimetype = mimetype; this.data = data; } public DataURL(String mimetype, String encoding, byte[] data) { this.mimetype = mimetype; this.encoding = encoding; this.data = data; } // ------------------------------------------------------------------------- public void setData(String data) { if("base64".equalsIgnoreCase(encoding)) { this.data = Base64.decode(data); } else { this.data = data.getBytes(); } } public void setData(byte[] data) { this.data = data; } public void setData(File file) { if(file != null) { try { setData(Files.readAllBytes(file.toPath())); } catch(Exception e) { e.printStackTrace(); } } } public void setData(URL url) { if(url != null) { try { setData(IOUtils.toByteArray(url.openStream())); } catch(Exception e) { e.printStackTrace(); } } } public void setEncoding(String encoding) { this.encoding = encoding; } public void setMimetype(String mimetype) { this.mimetype = mimetype; } public byte[] getData() { return data; } public InputStream getDataStream() { return new ByteArrayInputStream(data); } public String getEncoding() { return encoding; } public String getMimetype() { return mimetype; } // ------------------------------------------------------------------------- public String toExternalForm() { StringBuilder dataURL = new StringBuilder(""); dataURL.append("data:"); if(mimetype != null) dataURL.append(mimetype).append(";"); if(encoding != null) dataURL.append(encoding).append(","); if(data != null) { if("base64".equalsIgnoreCase(encoding)) { dataURL.append(Base64.encodeBytes(data)); } else { try { dataURL.append(new String(data,defaultStringEncoding)); } catch(Exception e) { e.printStackTrace(); } } } return dataURL.toString(); } public String toExternalForm(int options) { StringBuilder dataURL = new StringBuilder(""); dataURL.append("data:"); if(mimetype != null) dataURL.append(mimetype).append(";"); if(encoding != null) dataURL.append(encoding).append(","); if(data != null) { if("base64".equalsIgnoreCase(encoding)) { dataURL.append(Base64.encodeBytes(data, options)); } else { try { dataURL.append(new String(data,defaultStringEncoding)); } catch(Exception e) { e.printStackTrace(); } } } return dataURL.toString(); } // ------------------------------------------------------------------------- private void parseDataURL(String dataURL) throws MalformedURLException { if(dataURL != null && dataURL.length() > 0) { if(dataURL.startsWith("data:")) { dataURL = dataURL.substring("data:".length()); int mimeTypeEndIndex = dataURL.indexOf(';'); if(mimeTypeEndIndex > 0) { mimetype = dataURL.substring(0, mimeTypeEndIndex); dataURL = dataURL.substring(mimeTypeEndIndex+1); } int encodingEndIndex = dataURL.indexOf(','); if(encodingEndIndex > 0) { encoding = dataURL.substring(0, encodingEndIndex); dataURL = dataURL.substring(encodingEndIndex+1); } if("base64".equalsIgnoreCase(encoding)) { data = Base64.decode(dataURL); } else { data = dataURL.getBytes(); } } else { throw new MalformedURLException(); } } else { throw new MalformedURLException(); } } // ------------------------------------------------------------------------- @Override public boolean equals(Object o) { if(o != null) { if(o instanceof DataURL) { byte[] odata = ((DataURL) o).getData(); if(data != null && odata != null) { if(data.length == odata.length) { for(int i=0; i<data.length; i++) { if(data[i] != odata[i]) return false; } return true; } } } } return false; } @Override public int hashCode() { if(data != null) { return Arrays.deepHashCode(new Object[] { data } ); } else { return 0; } } // ------------------------------------------------------------------------- public File createTempFile() { File tempFile = null; try { byte[] bytes = this.getData(); if(bytes != null && bytes.length > 0) { String mimetype = this.getMimetype(); String prefix = "wandora" + this.hashCode(); String suffix = MimeTypes.getExtension(mimetype); if(suffix == null) suffix = "tmp"; if(!suffix.startsWith(".")) suffix = "."+suffix; tempFile = File.createTempFile(prefix, suffix); tempFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tempFile); fos.write(bytes); fos.close(); } } catch(Exception e) { e.printStackTrace(); } return tempFile; } // ------------------------------------------------------------------------- public static boolean isDataURL(String dataURLString) { if(dataURLString != null) { if(dataURLString.startsWith("data:")) { return true; } } return false; } public static String removeLineBreaks(String dataURLString) throws MalformedURLException { DataURL dataURL = new DataURL(dataURLString); dataURLString = dataURL.toExternalForm(Base64.DONT_BREAK_LINES); return dataURLString; } public static void saveToFile(String dataURLString, File file) throws MalformedURLException, IOException { DataURL dataURL = new DataURL(dataURLString); byte[] bytes = dataURL.getData(); FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } public void saveToFile(File file) throws MalformedURLException, IOException { byte[] bytes = getData(); FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } }
10,432
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JsonMapper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/JsonMapper.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.io.IOException; import java.io.StringWriter; import com.fasterxml.jackson.databind.ObjectMapper; /** * Transform java objects to JSON and vice versa. To get the JSON simply * use the writeValue method. If you don't want some fields in the java class * to be included, use the @JsonIgnore annotation. * * To parse JSON into java, use the readValue method with the java class you want * the results in. The Java class must have an anonymous constructor and suitable * getters/setters or public fields. * * * @author olli */ public class JsonMapper extends ObjectMapper { private static final long serialVersionUID = 1L; public JsonMapper(){ super(); } public String writeValue(Object value){ try{ StringWriter sw=new StringWriter(); writeValue(sw,value); return sw.toString(); }catch(IOException ioe){ioe.printStackTrace();} return null; } }
1,798
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Options.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Options.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Options.java * * Created on November 1, 2004, 3:26 PM */ package org.wandora.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * Options is a LinkedHashMap wrapper class. Options is used to store all * important settings in Wandora between use sessions. Options support XML * import and export. Import and export features use methods in XMLbox utility * class. * * Options converts XML paths to simple dot notation strings. * * @author akivela */ public class Options { private Map<String, String> options; private String resource; /** * Used to pick up all available options. * * @return Map with all options. */ public Map<String, String> asMap() { return options; } /** Creates a new instance of Options */ public Options(String optionsResource) { resource = optionsResource; options = new LinkedHashMap<>(); String optionsString = null; if(optionsResource.startsWith("http")) { //System.out.println("Reading options from URL '" + resource + "'."); try { optionsString = IObox.doUrl(new URL(resource)); } catch (Exception e) { e.printStackTrace(); } } else if(optionsResource.startsWith("file")) { try { String filename = resource.substring(7); //System.out.println("Reading options from file '" + filename + "'."); optionsString = IObox.loadFile(filename); //System.out.println("optionsString==" +optionsString); } catch (Exception e) { e.printStackTrace(); } } else { //System.out.println("Reading options from resource '" + resource + "'."); optionsString = IObox.loadResource(resource); } try { parseOptions(optionsString); } catch (Exception e) { e.printStackTrace(); } } public Options() { options=new LinkedHashMap<>(); } public Options(Options opts) { options=new LinkedHashMap<>(); options.putAll(opts.asMap()); } /** * Private method used to add indexes into an options key. * * @param key * @param fixAlsoLast Should method add explicit index to the last path part also * @return Fixed key containing indexes. */ private String fixIndexes(String key, boolean fixAlsoLast) { String[] parts = ((String) key).split("\\."); int endIndex = parts.length; if(parts != null && endIndex > 0) { key = ""; String part = null; for(int i=0; i<endIndex; i++) { part = parts[i]; if(fixAlsoLast || i < endIndex-1) { if(part.lastIndexOf("[") == -1) { part = part + "[0]"; } } if(i < endIndex-1) part = part + "."; key = key + part; } } return key; } private String fixIndexes(String key) { return fixIndexes(key, true); } /** * Returns value for the given key or defaultValue if key resolves no value. * * @param key Object ( * @param defaultValue * @return */ public String get(String key, String defaultValue) { String v=get(key); if(v==null) return defaultValue; else return v; } /** * Returns value for the given key. If key has no prefix "options." it is * added to the key. Also, key is modified by fixIndexes method. * * @param key String path for the returned value * @return String value stored in options with key or null if key resolves no value. */ public String get(String key) { if(key != null) { try { if(!key.startsWith("options.")) key = "options." + key; key = fixIndexes(key); //System.out.println("option request: "+key+" == "+options.get(key)); return options.get(key); } catch (Exception e) { e.printStackTrace(); } } return null; } /** * Shortcut method that returns options value as integer or 0 (zero) if * value can not be parsed to an integer. * * @param key String representing key path of the returned integer value. * @return Integer number stored to options with key or 0. */ public int getInt(String key) { return getInt(key, 0); } /** * Shortcut method that returns options value as integer or defaultValue if * value can not be converted to an integer. * * @param key String representing key path of the returned integer value. * @param defaultValue Integer number returned if key resolved value can not be * converted to an integer. * @return Integer number stored to options with key or defaultValue. */ public int getInt(String key, int defaultValue) { String sint = get(key); if(sint != null) { try { int val = Integer.parseInt(sint); return val; } catch (Exception e) {} } return defaultValue; } public double getDouble(String key) { return getDouble(key, 0.0); } public double getDouble(String key, double defaultValue) { String sd = get(key); if(sd != null) { try { double val = Double.parseDouble(sd); return val; } catch (Exception e) {} } return defaultValue; } public float getFloat(String key) { return getFloat(key, 0.0f); } public float getFloat(String key, float defaultValue) { String sd = get(key); if(sd != null) { try { float val = Float.parseFloat(sd); return val; } catch (Exception e) {} } return defaultValue; } public boolean getBoolean(String key, boolean defaultValue) { String s = get(key); if(s != null) { try { boolean val = Boolean.parseBoolean(s); return val; } catch (Exception e) { if("1".equals(s)) return true; if("0".equals(s)) return false; } } return defaultValue; } /** * Shortcut method to store integer numbers to options. * @param key * @param value Integer number that will be stored to options with key. */ public void put(String key, int value) { put(key, "" + value); } /** * Shortcut method to store double numbers to options. * @param key * @param value Double number to be stored to options. */ public void put(String key, double value) { put(key, "" + value); } /** * Shortcut method to store float numbers to options. * * @param key * @param value Float number to be stored to options. */ public void put(String key, float value) { put(key, "" + value); } /** * This is the actual put method every other put method uses. If key has no * "options." prefix, it is added to the key. If value is null then method * removes given key in options. * * @param key String key * @param value String value of the key */ public void put(String key, String value) { if(key != null) { if(!key.startsWith("options.")) key = "options." + key; key = fixIndexes(key); if(value == null) { options.remove(key); } else { options.put(key, value); } } } /** * Method iterates all values in options and returns first key i.e. * path that contains the key. If options contains no value string, * method returns null. * * @param value String representing options value. * @return String representing options path or null */ public String findKeyFor(String value) { if(value != null && options.containsValue(value)) { for(String key : options.keySet()) { if(value.equalsIgnoreCase(get(key))) return key; } } return null; } /** * Shortcut to discover boolean value of given options key. * * @param key String representing options path * @return true if value is "true" or "a". Returns false otherwise. */ public boolean isTrue(String key) { String val = get(key); if(val != null) { if("true".equalsIgnoreCase(val)) return true; if("1".equalsIgnoreCase(val)) return true; } return false; } /** * Shortcut method to discover boolean value of given options key. * * @param key String representing options path * @return true if value is not null, neither "false" or "0". Returns false otherwise. */ public boolean isFalse(String key) { String val = get(key); if(val != null) { if("false".equalsIgnoreCase(val)) return true; if("0".equalsIgnoreCase(val)) return true; } return false; } /** * Removes all key-value pairs that start with given key path string. * Method is used to clean up options. * * @param path String representing options path. */ public void removeAll(String path) { List<String> toBeDeletedKeys = new ArrayList<>(); if(!path.startsWith("options.")) path = "options."+path; path = this.fixIndexes(path, false); for(String key : options.keySet() ) { if(key.startsWith(path)) { toBeDeletedKeys.add(key); } } for( String key : toBeDeletedKeys ) { options.remove(key); } } /** * Adds all key-value pairs from a map into this one. * @param map The values to add. * @param prefix A prefix to add all key-value pairs. */ public void putAll(Map<String,String> map,String prefix){ if(prefix==null) prefix=""; for(Map.Entry<String,String> e : map.entrySet()){ put(prefix+e.getKey(),e.getValue()); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------ IO --- // ------------------------------------------------------------------------- /** * Parses given XML string and sets options to parsed content. This method * passes the parsing to parseOptions(String content, String encoding) * * @param content String containing valid XML document. */ public synchronized void parseOptions(String content) { parseOptions(content, null); } /** * Parses given XML string and sets options to parsed content. * @param content String containing valid XML document. * @param encoding String representing content encoding. */ public synchronized void parseOptions(String content, String encoding) { options = XMLbox.getAsMapTree(content, encoding); } public synchronized void parseOptions(BufferedReader reader) throws IOException { String line=null; StringBuilder sb=new StringBuilder(); while( (line=reader.readLine())!=null ){ sb.append(line).append("\n"); } parseOptions(sb.toString()); } public void print() { Object value; if(options.isEmpty()) { System.out.println(" no options available (size == 0)!"); } for(String key : options.keySet()) { value = options.get(key.toString()); System.out.println(" " + key + " == " + value); } } public void save(Writer out) throws IOException{ String optionsXML = XMLbox.wrapMap2XML(options); out.write(optionsXML); out.flush(); } public void save() { if(resource.startsWith("http:")) { return; } else if(resource.startsWith("file:")) { try { String filename=IObox.getFileFromURL(resource); // String filename = resource.substring(7); try { IObox.moveFile(filename, filename + ".bak"); } catch (Exception e) { e.printStackTrace(); } String optionsXML = XMLbox.wrapMap2XML(options); IObox.saveFile(filename, optionsXML); } catch (Exception e) { e.printStackTrace(); } } else { String path = "./resources/"; String resourcePath = path + resource; String optionsXML = XMLbox.wrapMap2XML(options); try { IObox.moveFile(resourcePath, resourcePath + ".bak"); } catch (Exception e) { e.printStackTrace(); } try { IObox.saveFile(resourcePath, optionsXML); } catch (Exception e) { e.printStackTrace(); } } } public Collection<String> keySet(){ List<String> copy=new ArrayList<>(); copy.addAll(options.keySet()); return copy; } }
14,417
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JarClassLoader.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/JarClassLoader.java
package org.wandora.utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandlerFactory; import java.util.Collection; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * * @author olli */ public class JarClassLoader extends URLClassLoader { protected File[] files; private static URL[] makeURLs(File[] files) throws MalformedURLException { URL[] ret=new URL[files.length]; for(int i=0;i<files.length;i++){ ret[i]=files[i].toURI().toURL(); } return ret; } public JarClassLoader(File file) throws MalformedURLException { this(new File[]{file}); } public JarClassLoader(File[] files, ClassLoader parent, URLStreamHandlerFactory factory) throws MalformedURLException { super(makeURLs(files), parent, factory); this.files=files; } public JarClassLoader(File[] files) throws MalformedURLException { super(makeURLs(files)); this.files=files; } public JarClassLoader(File[] files, ClassLoader parent) throws MalformedURLException { super(makeURLs(files), parent); this.files=files; } public Collection<String> listClasses() throws IOException { LinkedHashSet<String> ret=new LinkedHashSet<String>(); for(File f : files){ JarFile jf=new JarFile(f); try { Enumeration<? extends JarEntry> entries=jf.entries(); while(entries.hasMoreElements()){ JarEntry e=entries.nextElement(); if(!e.isDirectory()){ String name=e.getName(); if(name.endsWith(".class")){ name=name.substring(0,name.length()-6); name=name.replaceAll("[/\\\\]", "."); ret.add(name); } } } } finally { jf.close(); } } return ret; } public Collection<String> findServices(Class cls) throws IOException { return findServices(cls.getName()); } public Collection<String> findServices(String service) throws IOException { LinkedHashSet<String> ret=new LinkedHashSet<String>(); for(File f : files){ JarFile jf=new JarFile(f); try { JarEntry e=jf.getJarEntry("META-INF/services/"+service); if(e!=null){ InputStream is=jf.getInputStream(e); BufferedReader in=new BufferedReader(new InputStreamReader(is)); String line; while( (line=in.readLine())!=null ){ int commentInd=line.indexOf("#"); if(commentInd>=0) line=line.substring(0,commentInd); line=line.trim(); if(line.length()>0){ ret.add(line); } } } } finally { jf.close(); } } return ret; } }
3,475
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ScriptManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ScriptManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptException; /** * * @author olli */ public class ScriptManager { private Map<String,ScriptEngineFactory> engines; /** Creates a new instance of ScriptManager */ public ScriptManager() { engines = new LinkedHashMap<String,ScriptEngineFactory>(); } /** * Tries to match an engine key with an available scripting engine. Returns an * integer between 0 and 10. 0 means that engine does not match key at all and * 10 is exact match. Other values indicate quality of match, for example same * language but different engine name or matching language and engine but different * version. */ public int matchEngine(String key, ScriptEngineFactory f) { int score = 0; String[] info=key.split("\\s*;\\s*"); String e=f.getEngineName().replace(";","_"); if(e != null && info[0] != null) { if(e.equalsIgnoreCase(info[0])) { score = 10; } }; String l=f.getLanguageName().replace(";","_"); if(l != null && info[1] != null) { if(l.equalsIgnoreCase(info[1])) { score = Math.min(10, score+5); } } return score; } public static String getDefaultScriptEngine(){ return "Graal.js ; ECMAScript"; } public static String makeEngineKey(ScriptEngineFactory f){ String e=f.getEngineName().replace(";","_"); if(e==null) e=""; String l=f.getLanguageName().replace(";","_"); if(l==null) l=""; return e+" ; "+l; } public static List<String> getAvailableEngines(){ List<String> ret=new ArrayList<String>(); javax.script.ScriptEngineManager manager=new javax.script.ScriptEngineManager(); List<ScriptEngineFactory> fs=manager.getEngineFactories(); for(ScriptEngineFactory f : fs){ ret.add(makeEngineKey(f)); } return ret; } public ScriptEngine getScriptEngine(String engineInfo){ ScriptEngineFactory factory=engines.get(engineInfo); if(factory==null) { javax.script.ScriptEngineManager manager=new javax.script.ScriptEngineManager(); List<ScriptEngineFactory> fs=manager.getEngineFactories(); int bestScore=0; for(ScriptEngineFactory f : fs){ int s=matchEngine(engineInfo,f); if(s==10) { factory=f; break; } else if(s>bestScore){ bestScore=s; factory=f; } } engines.put(engineInfo,factory); } if(factory==null) return null; if(isGraal(factory)) { System.setProperty("polyglot.js.nashorn-compat", "true"); } ScriptEngine engine = factory.getScriptEngine(); if(engine != null) { try { if(isGraal(factory)) { Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("polyglot.js.allowAllAccess", true); bindings.put("polyglot.js.allowHostClassLookup", true); engine.eval("load('nashorn:mozilla_compat.js');"); } } catch(Exception e) {} } return engine; } public Object executeScript(String script) throws ScriptException { return executeScript(script,getScriptEngine(getDefaultScriptEngine())); } public Object executeScript(String script, ScriptEngine engine) throws ScriptException { Object o=engine.eval(script); return o; } private boolean isGraal(ScriptEngineFactory factory) { if(factory != null) { if(factory.getEngineName().equalsIgnoreCase("graal.js")) { return true; } } return false; } /** * This helper class is meant for creation of arrays in javascript. Mozilla * Rhino engine doesn't have an easy way to dynamically create array objects. * This helper class can be used like so: * * <code> * new ArrayBuilder(java.lang.String.class).add("foo").add("bar").add("qux").finalise() * </code> * * In actual Rhino code, leave out the .class after java.lang.String. */ public static class ArrayBuilder { public Class<?> cls; public ArrayList<Object> list; public ArrayBuilder(Class<?> cls){ this.cls=cls; list=new ArrayList<>(); } public ArrayBuilder add(Object o){ list.add(o); return this; } public Object finalise(){ Object array=java.lang.reflect.Array.newInstance(cls, list.size()); for(int i=0;i<list.size();i++){ Object o=list.get(i); java.lang.reflect.Array.set(array, i, o); } return array; } } }
6,239
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ByteBuffer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ByteBuffer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ByteBuffer.java * * Created on 18. maaliskuuta 2003, 16:26 */ package org.wandora.utils; /** * * @author akivela */ public class ByteBuffer { private static final int BUFFER=8192; private byte[] buffer; private int ptr; public ByteBuffer(){ buffer=new byte[BUFFER]; ptr=0; } public void append(byte[] b){ append(b,0,b.length); } public void append(byte[] b,int offs,int length){ if(ptr+length<=buffer.length){ System.arraycopy(b,offs,buffer,ptr,length); ptr+=length; } else{ int l=buffer.length; while(ptr+length>l){ l*=2; } byte[] n=new byte[l]; System.arraycopy(buffer,0,n,0,ptr); buffer=n; append(b,offs,length); } } public byte[] getArray() { return buffer; } public int getLength() { return ptr; } }
1,804
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RegexFileChooser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/RegexFileChooser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * RegexFileChooser.java * * Created on 30. joulukuuta 2004, 11:08 */ package org.wandora.utils; import java.io.File; import java.util.regex.Pattern; import javax.swing.filechooser.FileFilter; /** * * @author olli */ public class RegexFileChooser extends FileFilter{ public String description; public Pattern pattern; /** Creates a new instance of RegexFileChooser */ public RegexFileChooser(String regex,String description) { pattern=Pattern.compile(regex); this.description=description; } public boolean accept(File f){ if(f.isDirectory()) return true; return pattern.matcher(f.getAbsolutePath()).matches(); } public String getDescription(){ return description; } /** * Makes a RegexFileChooser for regular expression "(?i)^.*"+suffix+"$", that is, the * file must end with the given suffix (case insensitive). */ public static RegexFileChooser suffixChooser(String suffix,String description){ return new RegexFileChooser("(?i)^.*"+suffix+"$",description); } public static java.io.FileFilter ioFileFilter(final FileFilter ff){ return new java.io.FileFilter(){ public boolean accept(File pathname){ return ff.accept(pathname); } }; } }
2,147
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleNetAuthenticator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/SimpleNetAuthenticator.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.net.Authenticator.RequestorType; import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.URL; /** * * @author olli */ public class SimpleNetAuthenticator implements MultiNetAuthenticator.SingleAuthenticator { protected String host; protected String user; protected char[] password; public SimpleNetAuthenticator(String host, String user, String password){ this(host,user,password.toCharArray()); } public SimpleNetAuthenticator(String host, String user, char[] password){ this.host=host; this.user=user; this.password=password; } public SimpleNetAuthenticator(){} public String getHost() { return host; } public void setHost(String host) { this.host = host; } public char[] getPassword() { return password; } public void setPassword(char[] password) { this.password = password; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } @Override public PasswordAuthentication getPasswordAuthentication(String host, InetAddress addr, int port, String protocol, String prompt, String scheme, URL url, RequestorType reqType) { if(this.host.equalsIgnoreCase(host)) { return new PasswordAuthentication(user, password); } else return null; } }
2,297
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClipboardBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ClipboardBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ClipboardBox.java * * Created on 27. marraskuuta 2004, 13:26 */ package org.wandora.utils; import java.awt.Component; import java.awt.Image; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.text.JTextComponent; import org.wandora.utils.transferables.TransferableDataURL; import org.wandora.utils.transferables.TransferableImage; /** * This class provides methods to modify and retrieve information from the system * clipboard. * * @author akivela */ public class ClipboardBox { public static boolean makeDataURLs = true; /** Creates a new instance of ClipboardBox */ private ClipboardBox() { // Private } /** * Copies the selected text of the specified text component. */ public static void copy(Component c) { if(c != null) { if(c instanceof JTextComponent) { ((JTextComponent) c).copy(); } else { System.out.println("Copy event not handled!"); } } } /** * Cuts the selected text of the specified text component. */ public static void cut(Component c) { if(c != null) { if(c instanceof JTextComponent) { ((JTextComponent) c).cut(); } else { System.out.println("Cut event not handled!"); } } } /** * Pastes contents of the clipboard in the specified text component. */ public static void paste(Component c) { if(c != null) { if(c instanceof JTextComponent) { ((JTextComponent) c).paste(); } else { System.out.println("Paste event not handled!"); } } } /** * Returns the contents of the clipboard if it contains a string. * Otherwise returns null. */ public static String getClipboard() { Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); if(t == null) return null; try { if(t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List<File> files = (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); if(makeDataURLs) { for( File file : files ) { if(file != null) { DataURL dataURL = new DataURL(file); return dataURL.toExternalForm(); // CAN'T HANDLE MULTIPLE FILES. RETURN FIRST FILE AS A DATAURL. } } } else { String text = ""; for( File file : files ) { if(file != null) { if(text.length()>0) text+=";"; text += file.toURI().toString(); } } return text; } } else if(t.isDataFlavorSupported(DataFlavor.imageFlavor)) { BufferedImage image = (BufferedImage) t.getTransferData(DataFlavor.imageFlavor); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write( image, "png", baos ); baos.flush(); byte[] imageBytes = baos.toByteArray(); baos.close(); DataURL dataURL = new DataURL("image/png", imageBytes); return dataURL.toExternalForm(); } else if(t.isDataFlavorSupported(DataFlavor.stringFlavor)) { String text = (String)t.getTransferData(DataFlavor.stringFlavor); return text; } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } return null; } /** * Sets the contents of the clipboard. */ public static void setClipboard(String str) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if(DataURL.isDataURL(str)) { try { DataURL dataURL = new DataURL(str); if(dataURL.getMimetype().startsWith("image")) { BufferedImage image = ImageIO.read(new ByteArrayInputStream(dataURL.getData())); TransferableImage imageTransferable = new TransferableImage(image, str); clipboard.setContents(imageTransferable, null); return; } else { TransferableDataURL dataURLTransferable = new TransferableDataURL(dataURL); clipboard.setContents(dataURLTransferable, null); return; } } catch(Exception e) { // IGNORE } } StringSelection ss = new StringSelection(str); clipboard.setContents(ss, null); } /** * Sets the contents of the clipboard. Calls toString of the specified * object and sets the returned string in the clipboard. */ public static void setClipboard(Object o) { StringSelection ss = new StringSelection(o.toString()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); } /** * Sets the contents of the clipboard. */ public static void setClipboard(Image image) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); TransferableImage imgSel = new TransferableImage(image); clipboard.setContents(imgSel, null); } }
6,982
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GripCollections.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/GripCollections.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * GripCollections.java * * Created on 26. toukokuuta 2005, 12:37 */ package org.wandora.utils; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Vector; /** * This class provides some methods that make it easier to create and convert * between collections, arrays and maps. * * @author olli */ public class GripCollections { /** Creates a new instance of GripCollections */ public GripCollections() { } /** * Creates a Vector<T> from the T[] array. */ public static <T> Vector<T> arrayToCollection(T[] array){ return arrayToCollection(new Vector<T>(),array); } /** * Fills the given Collection with the elements of the given array and returns * the Collection. */ public static <T,C extends Collection<? super T>> C arrayToCollection(C c,T[] array){ for(T t : array){ c.add(t); } return c; } /** * Fills the given Collection with the other parameters and returns * the Collection. */ public static <T,C extends Collection<? super T>> C newCollection(C c,T ... objs){ return arrayToCollection(c,objs); } /** * Creates a new Vector<T>, fills it with the parameters and returns it. */ public static <T> Vector<T> newVector(T ... objs){ return newCollection(new Vector<T>(),objs); } /** * Creates a new HashSet<T>, fills it with the parameters and returns it. */ public static <T> HashSet<T> newHashSet(T ... objs){ return newCollection(new HashSet<T>(),objs); } /** * Creates a new T[] array where T is the same class as cls parameter and fills * it with elements of the given collection and then returns it. */ public static <T> T[] collectionToArray(Collection<? extends T> c,Class<T> cls){ T[] ts=(T[])java.lang.reflect.Array.newInstance(cls,c.size()); int ptr=0; for(T t : c){ ts[ptr++]=t; } return ts; } /** * Adds items from the specified array to the map. Items with even index * are used as keys of the items following them in the array. */ public static <K,V> Map<K,V> addArrayToMap(Map<K,V> map,Object[] items){ for(int i=0;i<items.length-1;i+=2){ map.put((K)items[i],(V)items[i+1]); } return map; } /** * Checks if there is at least one common element in the two specified * collections. */ public static boolean collectionsOverlap(Collection a,Collection b){ if(a.size()>b.size()){ Collection c=a; a=b; b=c; } for(Object o : a){ if(b.contains(o)) return true; } return false; } }
3,652
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MapEntry.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/MapEntry.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * MapEntry.java * * Created on 18. lokakuuta 2005, 14:45 */ package org.wandora.utils; import java.util.Map; /** * A simple class that implements java.util.Map.Entry. Needed to make own * Map implementations for entrySet method. * * @author olli */ public class MapEntry<K,V> implements Map.Entry<K,V> { private K key; private V value; /** Creates a new instance of MapEntry */ public MapEntry(K key,V value) { this.key=key; this.value=value; } public K getKey(){return key;} public V getValue(){return value;} public int hashCode(){ return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode()) ; // by api definition } public boolean equals(Object o){ if(o instanceof Map.Entry){ Map.Entry e=(Map.Entry)o; return (getKey()==null ? e.getKey()==null : getKey().equals(e.getKey())) && (getValue()==null ? e.getValue()==null : getValue().equals(e.getValue())); } else return false; } public V setValue(V value){ V old=this.value; this.value=value; return old; } }
2,043
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PriorityObject.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/PriorityObject.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * */ package org.wandora.utils; public class PriorityObject extends Object implements Comparable, java.io.Serializable { private static final long serialVersionUID = 1L; public final static int HIGHEST_PRIORITY = 10000; public final static int HIGHER_PRIORITY = 1000; public final static int DEFAULT_PRIORITY = 100; public final static int LOWER_PRIORITY = 10; public final static int LOWEST_PRIORITY = 1; protected int priority = DEFAULT_PRIORITY; protected Object object = null; public PriorityObject(Object object) { this.object = object; this.priority = DEFAULT_PRIORITY; } public PriorityObject(Object object, int priority) { this.object = object; this.priority = priority; } // ------------------------------------------------------------------------- public synchronized int getPriority() { return priority; } public synchronized void setPriority(int newPriority) { priority = newPriority; } public synchronized boolean isSuperior(PriorityObject priorityObject) { if (priorityObject != null) { if (priority > priorityObject.getPriority()) return true; } return false; } public int compareTo(Object o) { if (o != null && o instanceof PriorityObject) { if (priority > ((PriorityObject)o).getPriority()) return 1; if (priority < ((PriorityObject)o).getPriority()) return -1; return 0; } return 0; } // ------------------------------------------------------------------------- public synchronized Object getObject() { return object; } public synchronized void setObject(Object newObject) { object = newObject; } // ------------------------------------------------------------------------- public synchronized void adjustPriority( int amount ) { this.priority += amount; } public String toString() { if( null==object ) return "PriorityObject[null pri="+priority+"]"; else return "PriorityObject["+object.toString()+" pri="+priority+"]"; } }
3,101
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DHParamGenerator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/DHParamGenerator.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * DHParamGenerator.java * * Created on August 30, 2004, 11:50 AM */ package org.wandora.utils; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import javax.crypto.spec.DHParameterSpec; /** * * Use this class to generate modulus and base that can be used with DHParameterSpec in * Diffie-Hellman key exchange. * * @author olli */ public class DHParamGenerator { /** Creates a new instance of DHParamGenerator */ public DHParamGenerator() { } public static void main(String args[]) throws Exception { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH"); paramGen.init(1024); AlgorithmParameters params = paramGen.generateParameters(); DHParameterSpec paramSpec = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class); BigInteger modulus=paramSpec.getP(); BigInteger base=paramSpec.getG(); System.out.print("private static final BigInteger DHModulus = new BigInteger(1,new byte[]{"); outputBytes(modulus.toByteArray()); System.out.println("\n});"); System.out.print("private static final BigInteger DHBase = new BigInteger(1,new byte[]{"); outputBytes(base.toByteArray()); System.out.println("\n});"); } public static void outputBytes(byte[] bytes){ for(int i=0;i<bytes.length;i++){ if(i!=0) System.out.print(","); if(i%4==0) System.out.println(); int b=bytes[i]; if(b<0) b+=256; String s=Integer.toHexString(b); if(s.length()==1) s="0"+s; System.out.print("(byte)0x"+s); } } }
2,547
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XMLParamIf.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/XMLParamIf.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * XMLParamIf.java * * Created on September 9, 2004, 1:51 PM */ package org.wandora.utils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * <p> * This class allows you to make conditional statements in xml option files parsed * with XMLParamProcessor. This class is XMLParamAware and has its own parsing * of content elements. To use this class, do something along the lines of * </p> * <p><pre> * &lt;if xp:class="com.gripstudios.utils.XMLParamIf" xp:method="getObject"> * &lt;if xp:idref="someObject"/> * &lt;then>true value&lt;/then> * &lt;else>false value&lt;/else> * &lt;/if> * </pre></p> * <p> * If the object returned by if element is non null, a Boolean with value true or * a non boolean object, then the object then element evaluates to is returned by * getObject. Otherwise the object else element evaluates to is returned. If there * is no else element, then it returns null. * </p> * * @author olli */ public class XMLParamIf implements XMLParamAware { private Object object; public XMLParamIf(){ } public void xmlParamInitialize(Element element, XMLParamProcessor processor) { NodeList nl=element.getChildNodes(); Element test=null,then=null,els=null; for(int i=0;i<nl.getLength();i++){ Node n=nl.item(i); if(n instanceof Element){ Element e=(Element)n; if(e.getNodeName().equals("if")){ test=e; }else if(e.getNodeName().equals("then")){ then=e; }else if(e.getNodeName().equals("else")){ els=e; } } } try{ Object o=processor.createObject(test); if(o!=null && ( !(o instanceof Boolean) || ((Boolean)o).booleanValue() ) ){ object=processor.createObject(then); } else if(els!=null){ object=processor.createObject(els); } }catch(Exception e){ e.printStackTrace(); } } public Object getObject(){ return object; } }
2,984
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ParallelListenerList.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ParallelListenerList.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import static org.wandora.utils.Tuples.t2; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This is like ListenerList but several events can be firing simultaneously * in several threads. ListenerList synchronizes on the list itself meaning that * another event will not start processing until the previous one is done, this class * avoids that problem by using a different locking mechanism. * * This somewhat obfuscates the behaviour of modifying the list while events are * firing. Changes are still gathered into a separate changes list but those * changes are not processed until all currently firing events have finished. * If the changes list is not empty, processing of new events will wait until the * changes list has been cleared. * * @author olli */ public class ParallelListenerList <T> { protected final List<T> listeners; protected final List<Tuples.T2<T,Boolean>> changes; protected Class<T> cls; protected final Map<String,Method> methods; protected boolean returnValues=false; protected int iterating=0; public ParallelListenerList(Class<T> cls){ this.cls=cls; listeners=new ArrayList<T>(); changes=new ArrayList<Tuples.T2<T,Boolean>>(); methods=new HashMap<String,Method>(); } public int size(){ return listeners.size(); } public boolean isEmpty(){ return listeners.isEmpty(); } public boolean isReturnValues() { return returnValues; } public void setReturnValues(boolean returnValues) { this.returnValues = returnValues; } public void addListener(T l){ synchronized(changes){ if(iterating==0){ listeners.add(l); } else { changes.add(t2(l,true)); } } } public void removeListener(T l){ synchronized(changes){ if(iterating==0){ listeners.remove(l); } else { changes.add(t2(l,false)); } } } protected void processChanges(){ // you must hold the changes lock and iterating must be 0 before calling this for( Tuples.T2<T,Boolean> c : changes ){ if(c.e2) listeners.add(c.e1); else listeners.remove(c.e1); } changes.clear(); synchronized(changes){ // we should already have this lock, just do it again to avoid the warning of calling notifyAll outside synchronized block changes.notifyAll(); } } public Method findMethod(String event){ synchronized(methods){ Method m=methods.get(event); if(m==null){ if(!methods.containsKey(event)){ Method[] ms=cls.getMethods(); for(int i=0;i<ms.length;i++){ if(ms[i].getName().equals(event)) { m=ms[i]; break; } } methods.put(event,m); } } return m; } } public Object[] fireEvent(Method m,Object ... params){ return fireEventFiltered(m,null,params); } public Object[] fireEventFiltered(Method m,ListenerList.ListenerFilter<T> filter,Object ... params){ synchronized(changes){ while(!changes.isEmpty()) { try{ changes.wait(); }catch(InterruptedException ie){ return null; } } iterating++; } Object[] ret=null; try{ if(returnValues && m.getReturnType()!=null) ret=new Object[listeners.size()]; try{ for(int i=0;i<listeners.size();i++){ T l=listeners.get(i); if(filter==null || filter.invokeListener(l)){ if(ret!=null) ret[i]=m.invoke(l,params); else m.invoke(l, params); } } } catch(IllegalAccessException iae){ throw new RuntimeException(iae); } catch(InvocationTargetException ite){ throw new RuntimeException(ite); } } finally{ synchronized(changes){ iterating--; if(iterating==0 && !changes.isEmpty()) processChanges(); } } return ret; } public Object[] fireEvent(String event,Object ... params){ return fireEventFiltered(event,null,params); } public Object[] fireEventFiltered(String event,ListenerList.ListenerFilter<T> filter,Object ... params){ Method m=findMethod(event); if(m==null) throw new RuntimeException("Trying to fire event "+event+" but method not found."); return fireEventFiltered(m,filter,params); } public void forEach(ListenerList.EachDelegate delegate,Object ... params) { synchronized(changes){ while(!changes.isEmpty()) { try{ changes.wait(); }catch(InterruptedException ie){ return; } } iterating++; } try{ for(int i=0;i<listeners.size();i++){ T l=listeners.get(i); delegate.run(l,params); } } finally{ synchronized(changes){ iterating--; if(iterating==0 && !changes.isEmpty()) processChanges(); } } } public static interface EachDelegate<T> { public void run(T listener,Object ... params); } public static interface ListenerFilter<T> { public boolean invokeListener(T listener); } }
6,848
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Abortable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Abortable.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.awt.Frame; import javax.swing.SwingUtilities; import org.wandora.application.gui.UIBox; /** * * @author anttirt */ public class Abortable implements Runnable { public interface Impl extends Runnable { /** * shall not block and must be safe to call from another thread than run */ void forceAbort(); /** * can block; will be run in a separate thread */ void run(); } public enum Status { InProgress, Success, Failure } public interface ImplFactory { Impl create(Abortable parent); } private Impl impl; private Thread runThread; private Frame dialogParent; private AbortableProgressDialog dlg; private String name; private Status status; public Status getStatus() { return status; } private static Runnable abortProc(final Impl impl) { return new Runnable() { public void run() { impl.forceAbort(); }}; } private static Runnable runProc(final Impl impl) { return new Runnable() { public void run() { impl.run(); }}; } public Abortable(final Frame dialogParent, final ImplFactory fac, final Option<String> name) { if(fac == null) throw new NullPointerException("null ImplFactory passed to Abortable"); if(dialogParent == null) throw new NullPointerException("null dialog parent Frame passed to Abortable"); this.name = name.getOrElse(""); impl = fac.create(this); this.dialogParent = dialogParent; this.status = status.InProgress; } public void progress(final double ratio, final Status status, final String message) { this.status = status; if(dlg != null) { SwingUtilities.invokeLater( new Runnable() { public void run() { dlg.progress(ratio, status, message); } } ); } } /** * will block with dialog presented to user */ public void run() { runThread = new Thread(runProc(impl)); dlg = new AbortableProgressDialog(dialogParent, true, abortProc(impl), name); runThread.start(); UIBox.centerWindow(dlg, dialogParent); dlg.setVisible(true); } }
3,273
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ManualFileCopy.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ManualFileCopy.java
package org.wandora.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; public class ManualFileCopy implements Abortable.Impl { private volatile boolean abortRequested = false; private String inPath, outPath; private Abortable parent; public ManualFileCopy(Abortable parent, String outPath, String inPath) { this.inPath = inPath; this.outPath = outPath; this.parent = parent; } public void forceAbort() { abortRequested = true; } public static Abortable.ImplFactory factory(final String outPath, final String inPath) { return new Abortable.ImplFactory() { public Abortable.Impl create(Abortable parent) { return new ManualFileCopy(parent, outPath, inPath); } }; } public void run() { final boolean overWrite = false; try { File source = new File(new URI(inPath)); File target = new File(new URI(outPath)); if (!source.exists()) { } if (target.exists() && overWrite) { if (!target.delete()) { // can't overwrite, abort return; } } final long srcLength = source.length(); FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); byte[] data = new byte[8000]; int l = 0; long transferred = 0; int counter = 0; while (!abortRequested && (l = in.read(data)) > -1) { out.write(data, 0, l); transferred += 8000; ++counter; if (counter == 10) { counter = 0; parent.progress((double) transferred / (double) srcLength, Abortable.Status.InProgress, "Copy in progress."); } } in.close(); out.flush(); out.close(); parent.progress(1.0, Abortable.Status.Success, "File copy operation succeeded."); } catch (FileNotFoundException ex) { parent.progress(0.0, Abortable.Status.Failure, "File not found: " + ex.getMessage()); } catch (IOException ex) { parent.progress(0.0, Abortable.Status.Failure, "IO exception: " + ex.getMessage()); } catch (URISyntaxException e) { parent.progress(0.0, Abortable.Status.Failure, "Syntax error in SL URI: " + e.getMessage()); } } }
2,739
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XMLbox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/XMLbox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * */ package org.wandora.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringReader; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class XMLbox { public static Document getDocument( String contents ) { return getDocument(contents, null); } public static Document getDocument( String contents, String encoding ) { try { org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); try { parser.setFeature( "http://xml.org/sax/features/validation", false); parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false ); // NOTE THIS ADDED, HOPEFULLY NOBODY WANTED THIS METHOD DEFERRED? parser.setFeature( "http://apache.org/xml/features/dom/include-ignorable-whitespace", false ); parser.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); parser.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); } catch (SAXException e) { //LogWriter.println("WRN", "WRN parse(S): Couldn't set XML parser feature: "+e.getMessage()); } InputSource source = new InputSource( new StringReader( contents ) ); if(encoding != null) source.setEncoding(encoding); parser.parse(source); Document doc = parser.getDocument(); return doc; } catch( Exception e ) { e.printStackTrace(); } return null; } public static Hashtable getAsHashtable(String content) { return getAsHashtable(content, null); } public static Hashtable getAsHashtable(String content, String encoding) { Hashtable xmlHash = new Hashtable(); try { Document doc = getDocument(content, encoding); xmlHash = xml2Hash(doc); } catch (Exception e) { //LogWriter.println("ERR", "Unable to parse XML from content!"); } return xmlHash; } public static Hashtable xml2Hash(org.w3c.dom.Document doc) { Hashtable xmlHash = new Hashtable(); parse2Hashtable(doc.getDocumentElement(), "", xmlHash); return xmlHash; } public static String cleanForAttribute(String value){ value=value.replace("&","&amp;"); value=value.replace("\"","&quot;"); return value; } public static String cleanForXML(String value){ value=value.replace("&","&amp;"); value=value.replace("<","&lt;"); return value; } private static void parse2Hashtable(Node node, String key, Hashtable xmlHash) { NodeList nodes = node.getChildNodes(); int numOfNodes = nodes.getLength(); for( int nnum=0; nnum<numOfNodes; nnum++ ) { Node n = nodes.item(nnum); if( n.getNodeType()==Node.ELEMENT_NODE ) { String value = textValue((Element)n); int i = -1; String currentKey = null; do { i++; currentKey = key + "." + n.getNodeName() + "["+i+"]"; } while(xmlHash.get(currentKey) != null); if(null == value) { xmlHash.put(currentKey, ""); parseXML( n, currentKey, xmlHash ); } else { //System.out.println("parsed: "+currentKey+" == "+value); xmlHash.put(currentKey, value); } } else { // ignoring whitespace TEXT_NODEs } } } public static String wrapHash2XML(Hashtable h) { return hash2XML(wrapHash(h, ".")); } public static String hash2XML(Hashtable hash) { String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.getProperty("line.separator"); return prefix + hash2XML(hash, 0); } private static String hash2XML(Hashtable hash, int depth) { String br = System.getProperty("line.separator"); if(br == null) br = ""; String s = ""; String tab = ""; for(int i=0; i<depth; i++) { tab = tab + " "; } for(Enumeration keys = hash.keys(); keys.hasMoreElements(); ) { Object key = keys.nextElement(); Object value = hash.get(key); String keyStr = key.toString(); int index = keyStr.indexOf("["); if(index > 0) keyStr = keyStr.substring(0, index); if(value instanceof Hashtable) { s = s + tab + "<" + keyStr + ">" + br + hash2XML((Hashtable) value, depth+1) + tab + "</" + keyStr + ">" + br; } else { s = s + tab + "<" + keyStr + ">" + cleanForXML(value.toString()) + "</" + keyStr + ">" + br; } } return s; } // ------------------------------------------------------------------------- public static String wrapMap2XML(Map h) { return map2XML(wrapMap(h, ".")); } public static String map2XML(Map hash) { String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.getProperty("line.separator"); return prefix + map2XML(hash, 0); } private static String map2XML(Map hash, int depth) { String br = System.getProperty("line.separator"); if(br == null) br = ""; String s = ""; String tab = ""; for(int i=0; i<depth; i++) { tab = tab + " "; } for(Object key : hash.keySet() ) { Object value = hash.get(key); String keyStr = key.toString(); int index = keyStr.indexOf("["); if(index > 0) keyStr = keyStr.substring(0, index); if(value instanceof Map) { s = s + tab + "<" + keyStr + ">" + br + map2XML((Map) value, depth+1) + tab + "</" + keyStr + ">" + br; } else { s = s + tab + "<" + keyStr + ">" + cleanForXML(value.toString()) + "</" + keyStr + ">" + br; } } return s; } // ------------------------------------------------------------------------- public static Hashtable wrapHash(Hashtable hash, String delimiters) { Hashtable wrapped = new Hashtable(); for(Enumeration keys = hash.keys(); keys.hasMoreElements(); ) { Object key = keys.nextElement(); if(key instanceof String) { StringTokenizer address = new StringTokenizer((String) key, delimiters); Hashtable subhash = wrapped; String path = null; while(address.hasMoreTokens()) { path = address.nextToken(); if(address.hasMoreTokens()) { if(subhash.get(path) == null || !(subhash.get(path) instanceof Hashtable)) { subhash.put(path, new Hashtable()); } subhash = (Hashtable) subhash.get(path); } } if(hash.get(key) != null) { subhash.put(path, hash.get(key)); } } } return wrapped; } public static Hashtable getAsHashTree(String content) { return getAsHashTree(content, null); } public static Hashtable getAsHashTree(String content, String encoding) { Hashtable xmlHash = new Hashtable(); try { Document doc = getDocument(content, encoding); xmlHash = xml2HashTree(doc); } catch (Exception e) { //LogWriter.println("ERR", "Unable to parse XML from content!"); } return xmlHash; } // ------------- public static Map wrapMap(Map hash, String delimiters) { Map wrapped = new LinkedHashMap(); for(Object key : hash.keySet()) { if(key instanceof String) { StringTokenizer address = new StringTokenizer((String) key, delimiters); Map subhash = wrapped; String path = null; while(address.hasMoreTokens()) { path = address.nextToken(); if(address.hasMoreTokens()) { if(subhash.get(path) == null || !(subhash.get(path) instanceof Map)) { subhash.put(path, new LinkedHashMap()); } subhash = (Map) subhash.get(path); } } if(hash.get(key) != null) { subhash.put(path, hash.get(key)); } } } return wrapped; } public static Map getAsMapTree(String content) { return getAsMapTree(content, null); } public static Map getAsMapTree(String content, String encoding) { Map xmlMap = new LinkedHashMap(); try { Document doc = getDocument(content, encoding); xmlMap = xml2MapTree(doc); } catch (Exception e) { //LogWriter.println("ERR", "Unable to parse XML from content!"); } return xmlMap; } public static Hashtable xml2HashTree(org.w3c.dom.Document doc) { Hashtable xmlHash = new Hashtable(); Node rootNode = doc.getDocumentElement(); parseXML(rootNode, rootNode.getNodeName()+"[0]", xmlHash); return xmlHash; } private static void parseXML(Node node, String key, Hashtable xmlHash) { NodeList nodes = node.getChildNodes(); int numOfNodes = nodes.getLength(); for( int nnum=0; nnum<numOfNodes; nnum++ ) { Node n = nodes.item(nnum); if( n.getNodeType()==Node.ELEMENT_NODE ) { String value = textValue((Element)n); int i = -1; String currentKey = null; do { i++; currentKey = key + "." + n.getNodeName() + "["+i+"]"; } while(xmlHash.get(currentKey) != null); if(null == value) { xmlHash.put(currentKey, ""); parseXML( n, currentKey, xmlHash ); } else { //System.out.println("parsed: "+currentKey+" == "+value); xmlHash.put(currentKey, value); } } else { // ignoring whitespace TEXT_NODEs } } } public static Map xml2MapTree(org.w3c.dom.Document doc) { Map xmlMap = new LinkedHashMap(); Node rootNode = doc.getDocumentElement(); parseXML(rootNode, rootNode.getNodeName()+"[0]", xmlMap); return xmlMap; } private static void parseXML(Node node, String key, Map xmlMap) { NodeList nodes = node.getChildNodes(); int numOfNodes = nodes.getLength(); for( int nnum=0; nnum<numOfNodes; nnum++ ) { Node n = nodes.item(nnum); if( n.getNodeType()==Node.ELEMENT_NODE ) { String value = textValue((Element)n); int i = -1; String currentKey = null; do { i++; currentKey = key + "." + n.getNodeName() + "["+i+"]"; } while(xmlMap.get(currentKey) != null); if(null == value) { xmlMap.put(currentKey, ""); parseXML( n, currentKey, xmlMap ); } else { //System.out.println("parsed: "+currentKey+" == "+value); xmlMap.put(currentKey, value); } } else { // ignoring whitespace TEXT_NODEs } } } // ------------------------------------------------------------------------- public static String naiveGetAsText(String content) { String str = content; try { str = str.replaceAll("\\<script.*?\\>.*?\\<\\/script\\>", " "); str = str.replaceAll("\\<.+?\\>", " "); str = str.replaceAll("\\<\\\\.+?\\>", " "); str = str.replaceAll("\\<.+?\\\\\\>", " "); str = HTMLEntitiesCoder.decode(str); } catch (Exception e) { e.printStackTrace(); } return str; } public static String getAsText(String content, String encoding) { String str = content; try { Document doc = getDocument(content, encoding); str = xml2Text(doc); } catch (Exception e) { e.printStackTrace(); } return str; } public static String xml2Text(org.w3c.dom.Document doc) { StringBuffer sb = new StringBuffer(""); xml2Text(doc.getDocumentElement(), sb); return sb.toString().trim(); } private static void xml2Text(Node node, StringBuffer sb) { NodeList nodes = node.getChildNodes(); int numOfNodes = nodes.getLength(); for( int nnum=0; nnum<numOfNodes; nnum++ ) { Node n = nodes.item(nnum); if( n.getNodeType()==Node.ELEMENT_NODE ) { sb.append(" "); xml2Text( n, sb ); } else if( n.getNodeType()==Node.TEXT_NODE || n.getNodeType()==Node.CDATA_SECTION_NODE ) { String bit = n.getNodeValue().trim(); sb.append( bit ); if(!bit.endsWith("\n")) sb.append( " " ); } } } private static String textValue( Element e ) { StringBuffer text = new StringBuffer(""); NodeList nl = e.getChildNodes(); for( int i=0;i<nl.getLength();i++ ) { Node n = nl.item(i); if( n.getNodeType()==Node.TEXT_NODE || n.getNodeType()==Node.CDATA_SECTION_NODE ) { String bit = n.getNodeValue().trim(); text.append( bit ); } else { return null; } } return text.toString(); } public static String cleanUp( String xml ) { org.w3c.tidy.Tidy tidy = null; String tidyContent = null; try { xml = HTMLEntitiesCoder.decode(xml); Properties tidyProps = new Properties(); tidyProps.put("trim-empty-elements", "no"); tidy = new org.w3c.tidy.Tidy(); tidy.setConfigurationFromProps(tidyProps); tidy.setXmlOut(true); tidy.setXmlPi(true); tidy.setTidyMark(false); tidy.setWraplen(0); ByteArrayOutputStream tidyOutput = null; tidyOutput = new ByteArrayOutputStream(); tidy.parse(new ByteArrayInputStream(xml.getBytes()), tidyOutput); tidyContent = tidyOutput.toString(); } catch(Error er) { er.printStackTrace(); } return tidyContent; } }
16,768
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Option.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Option.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wandora.utils; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.utils.Functional.Fn0; import org.wandora.utils.Functional.Fn1; import org.wandora.utils.Functional.Pr1; /** * Use Option&lt;T&gt; instead of T as a function return or argument type to * signal that it might be null. The key benefit is that usage that might throw * NullPointerException is statically prevented by the compiler. Accessing the * value works either through iteration (option implements Iterable&lt;T&gt;) * or through the value() getter that throws a checked exception if the value * is null. * <br /> * To create a value, use Option.some(x) and to create a null object, * use Option.none(). To use a value, "iterate" over the value or use * a try/catch with the getter, or use one of the various member functions * to access the value in some other manner (for example mapping it to * a function or extracting the value with a default value) * <br /> * <code><pre> * for(Value val : tryGetItem()) * list.addItem(val); * * // as opposed to * * Value val = tryGetItem(); * if(val != null) * list.addItem(val); * * // or the potential NullPointerException situation: * Value val = tryGetItem(); * list.addItem(val); * </pre></code> * * Example usage (method of a class storing key/value pairs): * <code><pre> * class Storage&lt;KeyT, ValueT&gt; { * public Option&lt;ValueT&gt; get(KeyT key) { * ValueT value = find(key); * if(value == null) * return Option.none(); * else * return Option.some(value); * } * * ... * } * </pre></code> * * @author anttirt */ public class Option<T> implements Iterable<T> { /** * Creates an Option that contains a non-null value * @param The value to encapsulate * @return */ public static <T> Option<T> some(T val) { return new Option<T>(val); } /** * Returns an Option that represents null * @return */ public static <T> Option<T> none() { return none_; } /** * Creates an iterator that treats the Option as a list that contains * either 0 or 1 elements. * @return A new iterator over this Option instance */ public Iterator<T> iterator() { return new Iterator<T>() { private boolean iterationDone = false; public boolean hasNext() { if(iterationDone || value_ == null) return false; iterationDone = true; return true; } public T next() { return value_; } public void remove() { throw new UnsupportedOperationException("Attempted removal from Option"); } }; } /** * Essentially the map operation from functional programming where Option * is a list that contains either 0 or 1 elements. * @param f A function to call on the value contained in this instance. * @return some(delegate.invoke(value)) if value is not null, none() otherwise */ public <R> Option<R> map(final Delegate<R, ? super T> f) { if(value_ != null) return some(f.invoke(value_)); return none(); } /** * Essentially the map operation from functional programming where Option * is a list that contains either 0 or 1 elements. * @param f A function to call on the value contained in this instance. * @return some(delegate.invoke(value)) if value is not null, none() otherwise */ public <R> Option<R> map(final Fn1<R, ? super T> f) { if(value_ != null) return some(f.invoke(value_)); return none(); } /** * Essentially the map operation from functional programming where Option * is a list that contains either 0 or 1 elements. flatMap additionally * unwraps the result of the call to the passed function, so as to not * result in Option&lt;Option&lt;U&gt;&gt; where R = Option&lt;U&gt; * Also corresponds to the &gt;&gt;= operation for monads. * @param f A function to call on the value contained in this instance. * @return f.invoke(value) if value is not null, none() otherwise */ public <R> Option<R> flatMap(final Fn1<Option<R>, ? super T> f) { if(value_ != null) return f.invoke(value_); return none(); } /** * opt.apply(f) is the same as for(Object val : opt) f.invoke(val); * @param f The function that is invoked if a value exists */ public void apply(final Pr1<? super T> f) { if(value_ != null) f.invoke(value_); } /** * Gets the value of this Option or if no value exists returns the result of f * @param f The function to call if this Option is empty * @return value if not null, f.invoke() otherwise */ public T getOrElse(final Fn0<? extends T> f) { if(value_ != null) return value_; return f.invoke(); } /** * Gets the value of this Option or if no value exists, returns other * @param other The value to return if this Option is empty * @return value if not null, other otherwise */ public T getOrElse(final T other) { if(value_ != null) return value_; return other; } /** * Maps the value through f or if no value exists returns the result of g * @param f The function to call if a value exists * @param g The function to call otherwise * @return f.invoke(value) if value is not null, g.invoke() otherwise */ public <R> R mapOrElse(final Delegate<R, ? super T> f, final Fn0<R> g) { if(value_ != null) return f.invoke(value_); return g.invoke(); } /** * Maps the value through f or if no value exists returns other * @param f The function to call if a value exists * @param other The value to return otherwise * @return f.invoke(value) if value is not null, other otherwise */ public <R> R mapOrElse(final Delegate<R, ? super T> f, final R other) { if(value_ != null) return f.invoke(value_); return other; } /** * Maps the value through f or if no value exists returns the result of g * @param f The function to call if a value exists * @param g The function to call otherwise * @return f.invoke(value) if value is not null, g.invoke() otherwise */ public <R> R mapOrElse(final Fn1<R, ? super T> f, final Fn0<R> g) { if(value_ != null) return f.invoke(value_); return g.invoke(); } /** * Maps the value through f or if no value exists returns other * @param f The function to call if a value exists * @param other The value to return otherwise * @return f.invoke(value) if value is not null, other otherwise */ public <R> R mapOrElse(final Fn1<R, ? super T> f, final R other) { if(value_ != null) return f.invoke(value_); return other; } /** * Replaces this with other if this is empty, otherwise * yields this. * @param other * @return */ public Option<T> or(final Option<? extends T> other) { if(value_ != null) return this; if(other.value_ != null) return some(other.value_); return none(); } /** * Replaces this with other if this is empty, otherwise * yields this. * @param other * @return */ public Option<T> or(final T other) { if(value_ == null) { return some(other); } return this; } /** * Throws a checked exception if the value is null, * in order to prevent situations where NullPointerException * is thrown from arising. * @return The contained value. * @throws org.wandora.utils.Option.EmptyOptionException */ public T value() throws EmptyOptionException { if(value_ == null) throw new EmptyOptionException(); return value_; } /** * Checks whether this instance contains a value. * @return true if this instance contains a value. */ public boolean empty() { return value_ == null; } @Override public boolean equals(Object other) { // traverse potentially nested options recursively if(value_ instanceof Option) { return value_.equals(other); } else { if(other == null) return value_ == null; else return other.equals(value_); } } @Override public int hashCode() { int hash = 7; hash = 37 * hash + (this.value_ != null ? this.value_.hashCode() : 0); return hash; } /** * A checked exception that is thrown if the value getter * is used on an empty Option. */ public static class EmptyOptionException extends Exception { public EmptyOptionException() { super(); } } /** * Creates a collection containing only the actual values from a collection of options * @param col The Collection to filter * @return The resulting Collection of non-null values */ public static <T, C extends Collection<Option<T>>> Collection<T> somes(C col) { Collection<T> ret = new ArrayList(); for(Option<? extends T> opt : col) for(T val : opt) ret.add(val); return ret; } private Option() { value_ = null; } private Option(T val) { value_ = val; } private static final Option none_ = new Option(); private final T value_; /** * A convenience procedure that can be used with Option.apply to * add the value of an Option into a Collection: * <code><pre> * List&lt;String&gt; foo; * getOpt(bar).apply(Option.inserter(foo)); * </pre></code> * @param collection A Collection into which the value will be added if it exists * @return A function that inserts its argument into collection */ public static <U, C extends Collection<U>> Pr1<U> inserter(final C collection) { return new Pr1<U>() { public void invoke(U value) { collection.add(value); } }; } /** * A convenience procedure that can be used with Option.apply to * run the value of an Option&lt;T extends Runnable&gt; * <code><pre> * getProc().apply(Option.runner()); * </pre></code> * @return A function that calls .run() on its argument */ public static <U extends Runnable> Pr1<U> runner() { return new Pr1<U>() { public void invoke(U value) { value.run(); } }; } }
11,932
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Semaphore.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Semaphore.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Semaphore.java * * Created on 19. toukokuuta 2004, 15:25 */ package org.wandora.utils; /** * * @author olli */ public class Semaphore { private int counter; /** Creates a new instance of Semaphore */ public Semaphore(int counter) { this.counter=counter; } public synchronized void acquire() throws InterruptedException{ while(counter==0) this.wait(); counter--; } public synchronized void release(){ counter++; this.notify(); } }
1,346
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NativeFileCopy.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/NativeFileCopy.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wandora.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; /** * Uses a system-specific copy command provided in wandora's config with the name "copycommand" */ public class NativeFileCopy implements Abortable.Impl { private Process process; private Abortable parent; private String destination; private String source; private String[] copyCommand; public NativeFileCopy(Abortable parent, String destination, String source, String[] copyCommand) { this.parent = parent; this.destination = destination; this.source = source; this.copyCommand = copyCommand; } public void forceAbort() { if(process != null) { synchronized(process) { process.notify(); } } } public static Abortable.ImplFactory factory(final String[] copyCommand, final String destination, final String source) { return new Abortable.ImplFactory() { public Abortable.Impl create(final Abortable parent) { return new NativeFileCopy(parent, destination, source, copyCommand); } }; } public static <T> T[] concat(T[] dest, T[] src0, T... src1) { int i = 0; for(; i < src0.length; ++i) { dest[i] = src0[i]; } for(int j = 0; j < src1.length; ++j, ++i) { dest[i] = src1[j]; } return dest; } public void run() { try { final String inPath = new File(new URI(source)).getCanonicalPath(), outPath = new File(new URI(destination)).getCanonicalPath(); parent.progress(0.0, Abortable.Status.InProgress, "Copy operation in progress " + "(copying to \"" + destination + "\")"); String[] args = concat(new String[copyCommand.length + 2], copyCommand, inPath, outPath); /*{ String intr = "["; for(String str : args) { System.err.print(intr + str); intr = ", "; } System.err.print("]\n"); }*/ process = Runtime.getRuntime().exec(args); final int result = process.waitFor(); InputStream stream = process.getErrorStream(); if (result != 0) { byte[] data = new byte[stream.available()]; stream.read(data); parent.progress(0.0, Abortable.Status.Failure, "Copy operation failed with " + "return code " + result + "\nProcess stderr:\n" + new String(data)); } else { parent.progress(1.0, Abortable.Status.Success, "Copy operation succeeded!"); } } catch(InterruptedException e) { process.destroy(); parent.progress(0.0, Abortable.Status.Failure, "The thread was interrupted before " + "the copy operation completed; " + "child process terminated."); } catch(SecurityException e) { parent.progress(0.0, Abortable.Status.Failure, "No permission to start subprocess; " + "grant permission or remove \"copycommand\" " + "from wandora configuration."); } catch(IOException e) { parent.progress(0.0, Abortable.Status.Failure, "IO exception: " + e.getMessage() + "\nMake sure the \"copycommand\" tag " + "in conf/options.xml is set " + "to the correct system-specific copy " + "command (such as /bin/cp or cmd /c copy) " + "or alternatively, remove it and a slower " + "file copy through java file streams " + "will be used."); } catch(URISyntaxException e) { parent.progress(0.0, Abortable.Status.Failure, "Invalid SI: " + e.getMessage()); } } }
6,036
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MSOfficeBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/MSOfficeBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * MSOfficeBox.java * * Created on 13.6.2006, 14:20 * */ package org.wandora.utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Iterator; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.POITextExtractor; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.hwpf.model.TextPiece; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; /** * Class to extract the text from MS office documents. * Based on Apache's POI framework * * @author akivela */ public class MSOfficeBox { /** * Creates a new instance of MSOfficeBox */ private MSOfficeBox() { // Private } // ----------------------------------------------------------- WORD TEXT --- public static String getWordTextOld(InputStream is) { try { return getWordTextOld(new HWPFDocument(is)); } catch(Exception e) { e.printStackTrace(); } return null; } /** * Get the text from the word file, as an array with one String * per paragraph */ public static String[] getWordParagraphText(HWPFDocument doc) { String[] ret; // Extract using the model code try { Range r = doc.getRange(); ret = new String[r.numParagraphs()]; for(int i=0; i<ret.length; i++) { Paragraph p = r.getParagraph(i); ret[i] = p.text(); // Fix the line ending if(ret[i].endsWith("\r")) { ret[i] = ret[i] + "\n"; } } } catch(Exception e) { // Something's up with turning the text pieces into paragraphs // Fall back to ripping out the text pieces ret = new String[1]; ret[0] = getWordTextFromPieces(doc); } return ret; } /** * Grab the text out of the text pieces. Might also include various * bits of crud, but will work in cases where the text piece -> paragraph * mapping is broken. Fast too. */ public static String getWordTextFromPieces(HWPFDocument doc) { StringBuilder textBuf = new StringBuilder(); Iterator<TextPiece> textPieces = doc.getTextTable().getTextPieces().iterator(); while (textPieces.hasNext()) { TextPiece piece = textPieces.next(); String encoding = "Cp1252"; if (piece.isUnicode()) { encoding = "UTF-16LE"; } try { String text = new String(piece.getRawBytes(), encoding); textBuf.append(text); } catch(UnsupportedEncodingException e) { throw new InternalError("Standard Encoding " + encoding + " not found, JVM broken"); } } String text = textBuf.toString(); // Fix line endings (Note - won't get all of them text = text.replaceAll("\r\r\r", "\r\n\r\n\r\n"); text = text.replaceAll("\r\r", "\r\n\r\n"); if(text.endsWith("\r")) { text += "\n"; } return text; } /** * Grab the text, based on the paragraphs. Shouldn't include any crud, * but slightly slower than getTextFromPieces(). */ public static String getWordTextOld(HWPFDocument doc) { StringBuilder ret = new StringBuilder(); String[] text = getWordParagraphText(doc); for(int i=0; i<text.length; i++) { ret.append(text[i]); } return ret.toString(); } public static String getWordText(InputStream is) { WordExtractor extractor = null; try { extractor = new WordExtractor(is); return extractor.getText(); } catch(Exception e) { e.printStackTrace(); } finally { if(extractor != null ) { try { extractor.close(); } catch(Exception ex) {}; } } return null; } // ----------------------------------------------------------------- Any --- public static String getText(URL url) { try { return getText(url.openStream()); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getDocxText(File file) { XWPFWordExtractor extractor = null; try { XWPFDocument docx = new XWPFDocument(new FileInputStream(file)); extractor = new XWPFWordExtractor(docx); String text = extractor.getText(); return text; } catch(Exception e) { e.printStackTrace(); } finally { if(extractor != null ) { try { extractor.close(); } catch(Exception ex) {}; } } return null; } public static String getText(InputStream is) { try { POITextExtractor extractor = ExtractorFactory.createExtractor(is); return extractor.getText(); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(File f) { try { POITextExtractor extractor = ExtractorFactory.createExtractor(f); return extractor.getText(); } catch(Exception e) { e.printStackTrace(); } return null; } }
6,314
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EasyReplaceExpression.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/EasyReplaceExpression.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * EasyReplaceExpression.java * * Created on 11.6.2005, 16:18 */ package org.wandora.utils; import java.util.regex.Pattern; /** * * @author akivela */ public class EasyReplaceExpression { boolean isCaseInsensitive; boolean findInsteadMatch; Pattern pattern; String replacement; String name; /** Creates a new instance of EasyPattern */ public EasyReplaceExpression() { } /** Creates a new instance of KirjavaPattern */ public EasyReplaceExpression(String n, String ps, String rep, boolean findInstead, boolean caseInsensitive) { try { name = n; isCaseInsensitive = caseInsensitive; if(isCaseInsensitive) pattern = Pattern.compile(ps, Pattern.CASE_INSENSITIVE); else pattern = Pattern.compile(ps); replacement = rep; findInsteadMatch = findInstead; } catch (Exception e) { System.out.println(e); } } public EasyReplaceExpression(String n, Pattern p, String rep, boolean findInstead, boolean caseInsensitive) { try { name = n; isCaseInsensitive = caseInsensitive; if(isCaseInsensitive) pattern = Pattern.compile(p.toString(), Pattern.CASE_INSENSITIVE); else pattern = Pattern.compile(p.toString()); replacement = rep; findInsteadMatch = findInstead; } catch (Exception e) { System.out.println(e); } } public boolean matches(String s) { if(pattern != null && s != null) { if(findInsteadMatch) return pattern.matcher(s).find(); else return pattern.matcher(s).matches(); } return false; } public Pattern getPattern() { return pattern; } public String getPatternString() { if(pattern != null) return pattern.toString(); return ""; } public String getReplacementString() { return replacement != null ? replacement : ""; } public boolean findInsteadMatch() { return findInsteadMatch; } public boolean isCaseInsensitive() { return isCaseInsensitive; } public String getName() { return name; } }
3,155
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EasyVector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/EasyVector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * EasyVector.java * * Created on June 19, 2001, 4:48 PM */ package org.wandora.utils; import java.util.Vector; /** * * @author olli */ public class EasyVector extends Vector { /** Creates new EasyVector */ public EasyVector(Object[] o) { for(int i=0;i<o.length;i++){ this.add(o[i]); } } }
1,147
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
KeyedHashSet.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/KeyedHashSet.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * KeyedHashSet.java * * Created on 18. lokakuuta 2005, 15:45 */ package org.wandora.utils; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * * @author olli */ public class KeyedHashSet<E> implements Set<E> { protected KeyedHashMap<E,Object> map; protected Delegate<String,E> keyMaker; /** Creates a new instance of KeyedHashSet */ public KeyedHashSet(Delegate<String,E> keyMaker) { this.keyMaker=keyMaker; map=new KeyedHashMap<E,Object>(keyMaker); } public boolean add(E o){ return map.put(o,o)==null; } public boolean addAll(Collection<? extends E> c){ boolean ret=false; for(E e : c){ ret^=add(e); } return ret; } public void clear(){ map=new KeyedHashMap<E,Object>(keyMaker); } public boolean contains(Object o){ return map.containsKey(o); } public boolean containsAll(Collection<?> c){ for(Object o : c){ if(!map.containsKey(o)) return false; } return true; } public boolean equals(Object o){ if(o instanceof Set){ if(((Set)o).size()!=this.size()) return false; return this.containsAll((Set)o); } else return false; } public int hashCode(){ int hashCode=0; for(E e : map.keySet()){ hashCode+=e.hashCode(); } return hashCode; } public boolean isEmpty(){ return map.isEmpty(); } public Iterator<E> iterator(){ return map.keySet().iterator(); } public boolean remove(Object o){ return map.remove(o)!=null; } public boolean removeAll(Collection<?> c){ boolean changed=false; for(Object o : c ){ changed^=(map.remove(o)!=null); } return changed; } public boolean retainAll(Collection<?> c){ throw new UnsupportedOperationException(); } public int size(){ return map.size(); } public Object[] toArray(){ Object[] a=new Object[size()]; int ptr=0; for(E e : map.keySet()){ a[ptr++]=e; } return a; } public <T> T[] toArray(T[] a){ throw new RuntimeException("Not implemented"); } }
3,151
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Textbox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Textbox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * TextTools.java * * Created on 24. helmikuuta 2003, 13:28 */ package org.wandora.utils; import java.awt.Color; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.StyledDocument; import javax.swing.text.rtf.RTFEditorKit; /** * Textbox is an utility class providing useful text manipulation and processing * services as static methods. Some methods here are reserved for historical * reasons. * * @author akikivela */ public class Textbox { /** Creates a new instance of TextTools */ public Textbox() { } /** * Makes a String representation of a map. Useful for debugging. * * @param map * @return */ public static String mapToString(Map map){ StringBuilder buf=new StringBuilder(); Iterator iter=map.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); buf.append(e.getKey().toString()).append(" => ").append(e.getValue().toString()).append(",\n"); } return buf.toString(); } public static java.util.List<String> capitalizeFirst(java.util.List<String> words) { java.util.List<String> newWords = new ArrayList<String>(); if (words != null) { for (int i=0; i<words.size(); i++) { newWords.add(capitalizeFirst(words.get(i))); } } return newWords; } public static String capitalizeFirst(String word) { if(word != null) { if(word.length()>0) { String first = word.substring(0, 1).toUpperCase(); if(word.length()>1) { return first + word.substring(1); } else { return first; } } } return word; } public static String makeHTMLParagraph(String text, int width) { if(text == null) return null; int l = text.length(); StringBuilder sb = new StringBuilder(l); int pl = 0; for(int i=0; i<l; i++) { if(pl++ < width) sb.append(text.charAt(i)); else { int c = text.charAt(i); if(c == ' ') { sb.append("<br>"); pl = 0; } else sb.append((char) c); } } return "<html>" + sb.toString() + "</html>"; } public static String getSlice(String text, String delimiter, int sliceNumber) { String slice = ""; try { java.util.List<String> slices = slice(text, delimiter); if(slices.size() > sliceNumber) { slice = slices.get(sliceNumber); } } catch (Exception e) {} if("".equals(slice) && sliceNumber == 0) { slice = text; } return slice; } public static java.util.List<String> slice(String text, String delimiter) { java.util.List<String> slices = new ArrayList<String>(); String slice; if (text != null && delimiter != null) { while(text.length() > delimiter.length()) { try { if (text.contains(delimiter)) { slice = text.substring(0, text.indexOf(delimiter)); slices.add(slice); text = text.substring(text.indexOf(delimiter) + delimiter.length()); } else { //LogWriter.println("No more delimiters found!"); slices.add(text); text = ""; } } catch (Exception e) { System.out.println("Exception '" + e.toString() + "' occurred while slicing text!"); } } } else { System.out.println("Either text or delimiter is null! Unable to slice given text!"); } return slices; } public static java.util.List sliceWithRE(String text, String regularExpression) { java.util.List<String> sliceList = new ArrayList<String>(); try { if(text != null && regularExpression != null) { String[] slices = text.split(regularExpression); for(String slice : slices) { if(slice != null && slice.length() > 0) { sliceList.add(slice); } } } } catch(Exception e) { e.printStackTrace(); } return sliceList; } public static String filterNonAlphaNums(String string) { StringBuilder newString = new StringBuilder(); char c; if(string != null) { for(int i=0; i<string.length(); i++) { c = string.charAt(i); if(Character.isLetterOrDigit(c)) { newString.append(c); } else newString.append('_'); } } return newString.toString(); } public static String toLowerCase(String string) { if(string != null) { return string.toLowerCase(); } return null; } public static java.util.List<String> encode(java.util.List<String> strings, String charset) { java.util.List<String> newStrings = new ArrayList<String>(); for (int i=0; i < strings.size(); i++) { try { newStrings.add(encode(strings.get(i), charset)); } catch (Exception e) { System.out.println("Exception '" + e.toString() + "' occurred while encoding vector of strings!"); } } return newStrings; } public static String encode(String string, String charset) { if (charset != null && charset.length()>0) { if(charset.equalsIgnoreCase("UTF-8") || charset.equalsIgnoreCase("UNICODE")) { try { return new String(string.getBytes(), charset); } catch (Exception e) { System.out.println("Unable to convert '" + string + "' to '" + charset + "."); } } else if(charset.equalsIgnoreCase("URL_ENCODE")) { return java.net.URLEncoder.encode(string); } } return string; } /** * Transforms all XML specific characters to character entities and * Windows new line characters to simple unix style new line characters. * * @param s * @return Encoded XML string. */ public static String encodeXML(String s) { if(s != null) { s = s.replace("&", "&amp;"); s = s.replace(">", "&gt;"); s = s.replace("<", "&lt;"); s = s.replace("\\n\\r", "\\n"); } return s; } /** * Reverses a name such as "Doe, John" to "John Doe". * * @param name * @return Reversed name. */ public static String firstNameFirst(String name) { if(name != null) { int commaIndex = name.indexOf(","); if(commaIndex > -1) { String fname = name.substring(commaIndex+1); String lname = name.substring(0, commaIndex); return fname.trim() + " " + lname.trim(); } } return name; } /** * Reverses a name such as "John Doe" to "Doe, John". * * @param name * @return Reversed name. */ public static String reverseName(String name) { String reversedName = name; try { if (name != null && name.length() > 0) { java.util.List<String> nameSlices = Textbox.slice(name, " "); String nameSlice = null; if(nameSlices.size() > 1) { nameSlice = (String) nameSlices.get(nameSlices.size() - 1); if(Character.isUpperCase(nameSlice.charAt(0))) { reversedName = nameSlice; String firstNames = ""; for(int i=0; i<nameSlices.size()-1; i++) { nameSlice = (String) nameSlices.get(i); if(Character.isUpperCase(nameSlice.charAt(0))) { firstNames = firstNames + " " + nameSlice; } } if(firstNames.length() > 0) { reversedName = reversedName + "," + firstNames; } } } } } catch (Exception e) { reversedName = name; } return reversedName; } /** * Checks if a string has any other characters than white space characters. * If the string has only white space characters, method returns true. The * String is "meaningless". Otherwise method returns false. * * @param string * @return true if the string has only white space characters. Otherwise false. */ public static boolean meaningless(String string) { if (string != null) { if (string.length() > 0) { for (int i=0; i<string.length(); i++) { if (!Character.isWhitespace(string.charAt(i))) { return false; } } } } return true; } public static String removeQuotes(String quoted) { try { if (quoted != null) { if (quoted.length() > 0) { if(quoted.startsWith("\"")) { if(quoted.endsWith("\"")) { quoted = quoted.substring(1, quoted.length()-1); } else { quoted = quoted.substring(1); } } } } } catch (Exception e) { System.out.println("Catched exception in remove quotes (Textbox)"); e.printStackTrace(); } return quoted; } public static String[][] makeStringTable(String s) { java.util.List<java.util.List<String>> lines = new ArrayList(); java.util.List<String> linev; String line; StringTokenizer st = new StringTokenizer(s, "\n"); StringTokenizer st2; int maxc = 0; while(st.hasMoreTokens()) { line = st.nextToken(); linev = new ArrayList(); st2 = new StringTokenizer(line, "\t"); int c = 0; while(st2.hasMoreTokens()) { linev.add(st2.nextToken()); c++; } lines.add(linev); maxc = Math.max(maxc, c); } int maxl = lines.size(); String[][] table = new String[lines.size()][maxc]; for(int i=0; i<maxl; i++) { java.util.List<String> v = lines.get(i); for(int j=0; j<maxc; j++) { try { table[i][j] = v.get(j); } catch (Exception e) { table[i][j] = null; } } } return table; } public static String sortStringVector(Vector v) { String[] a = new String[v.size()]; String t = null; v.toArray(a); for(int i=a.length-1; i>0; i--) { for(int j=0; j<i; j++) { if(a[i].compareTo(a[j]) < 0) { t = a[i]; a[i] = a[j]; a[j] = t; } } } StringBuilder sb = new StringBuilder(""); for(int i=0; i<a.length; i++) { sb.append(a[i] + "\n"); } return sb.toString(); } /** * Method creates a string array from objects in given vector. * * @param v The vector containing strings to be attached to the generated string. * @return Method returns an array containing string picked out of given vector. * If vector contains no strings null is returned. */ public static String[] vectorToStringArray(Vector v) { String[] a = null; if (v != null && v.size() > 0) { a = new String[v.size()]; for (int i=0; i<v.size(); i++) { try { a[i] = (String) v.elementAt(i); } catch (Exception e) { e.printStackTrace(); } } } return a; } // ------------------------------------------------------------------------- /** * Trims both starting and ending white space characters of a string. * This method is here for historical reasons. * * @param string * @return */ public static String trimExtraSpaces(String string) { return trimEndingSpaces(trimStartingSpaces(string)); } /** * Trims all ending white space characters of a string. Delegates the * action to method trimEndingSpaces. * * @param text * @return */ public static String chop(String text) { return trimEndingSpaces(text); } /** * Trims all ending white space characters of a string. This method is * here for historical reasons. * * @param string * @return */ public static String trimEndingSpaces(String string) { if (string != null) { int i = string.length()-1; while(i > 0 && Character.isWhitespace(string.charAt(i))) i--; string = string.substring(0, i+1); } return string; } /** * Trims all starting white space characters of a string. This method is * here for historical reasons. * * @param string * @return */ public static String trimStartingSpaces(String string) { if (string != null) { int i = 0; while(i < string.length() && Character.isWhitespace(string.charAt(i))) i++; string = string.substring(i); } return string; } // ------------------------------------------------------------------------- /** * Returns hexadecimal string representing a color. Color is given as * an argument. Hexadecimal string resembles color codes used in HTML and * CSS but doesn't contain the hash prefix. For example, this method returns * string "ffffff" for the white color and "ff0000" for the red color. * * @param color is the color we want the HTML code. * @return String representing color's HTML code. */ public static String getColorHTMLCode(Color color) { StringBuilder colorName = new StringBuilder(""); int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); String code = Integer.toHexString(red); if(code.length() < 2) code = "0" + code; colorName.append(code); code = Integer.toHexString(green); if(code.length() < 2) code = "0" + code; colorName.append(code); code = Integer.toHexString(blue); if(code.length() < 2) code = "0" + code; colorName.append(code); //System.out.println("color: " + colorName.toString()); return colorName.toString(); } /** * Reads RTF text from an input stream and returns plain text. * Method uses Java's RTFEditorKit for the transformation. * * @param in is input stream to be transformed. * @return String that contains the RTF text as a plain text. * @throws IOException if the input stream doesn't resolve RTF document. */ public static String RTF2PlainText(InputStream in) throws IOException { StyledDocument doc=new DefaultStyledDocument(); RTFEditorKit kit=new RTFEditorKit(); try { kit.read(in,doc,0); return doc.getText(0,doc.getLength()); } catch(BadLocationException e) { e.printStackTrace(); return null; } } }
17,671
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
FileTypes.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/FileTypes.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * FileTypes.java * * Created on 27.7.2006, 17:16 * */ package org.wandora.utils; import java.util.HashMap; import java.util.Map; /** * This class provides mappings between commonly used file suffixes and * content types. * * @author olli */ public class FileTypes { /** * Maps file suffixes to content types. There may be several suffixes * mapping to same content type. */ public static Map<String,String> suffixToType=GripCollections.addArrayToMap(new HashMap<String,String>(),new Object[]{ "a","application/octet-stream", "ai","application/postscript", "aif","audio/x-aiff", "aifc","audio/x-aiff", "aiff","audio/x-aiff", "arc","application/octet-stream", "au","audio/basic", "avi","application/x-troff-msvideo", "bcpio","application/x-bcpio", "bin","application/octet-stream", "c","text/plain", "c++","text/plain", "cc","text/plain", "cdf","application/x-netcdf", "cpio","application/x-cpio", "djv","image/x-djvu", "djvu","image/x-djvu", "dump","application/octet-stream", "dvi","application/x-dvi", "eps","application/postscript", "etx","text/x-setext", "exe","application/octet-stream", "gif","image/gif", "gtar","application/x-gtar", "gz","application/octet-stream", "h","text/plain", "hdf","application/x-hdf", "hqx","application/octet-stream", "htm","text/html", "html","text/html", "iw4","image/x-iw44", "iw44","image/x-iw44", "ief","image/ief", "java","text/plain", "jfif","image/jpeg", "jfif-tbnl","image/jpeg", "jpe","image/jpeg", "jpeg","image/jpeg", "jpg","image/jpeg", "latex","application/x-latex", "man","application/x-troff-man", "me","application/x-troff-me", "mime","message/rfc822", "mov","video/quicktime", "movie","video/x-sgi-movie", "mpe","video/mpeg", "mpeg","video/mpeg", "mpg","video/mpeg", "ms","application/x-troff-ms", "mv","video/x-sgi-movie", "nc","application/x-netcdf", "o","application/octet-stream", "oda","application/oda", "pbm","image/x-portable-bitmap", "pdf","application/pdf", "pgm","image/x-portable-graymap", "pl","text/plain", "pnm","image/x-portable-anymap", "ppm","image/x-portable-pixmap", "ps","application/postscript", "qt","video/quicktime", "ras","image/x-cmu-rast", "rgb","image/x-rgb", "roff","application/x-troff", "rtf","application/rtf", "rtx","application/rtf", "saveme","application/octet-stream", "sh","application/x-shar", "shar","application/x-shar", "snd","audio/basic", "src","application/x-wais-source", "sv4cpio","application/x-sv4cpio", "sv4crc","application/x-sv4crc", "t","application/x-troff", "tar","application/x-tar", "tex","application/x-tex", "texi","application/x-texinfo", "texinfo","application/x-texinfo", "text","text/plain", "tif","image/tiff", "tiff","image/tiff", "tr","application/x-troff", "tsv","text/tab-separated-values", "txt","text/plain", "ustar","application/x-ustar", "uu","application/octet-stream", "wav","audio/x-wav", "wsrc","application/x-wais-source", "xbm","image/x-xbitmap", "xpm","image/x-xpixmap", "xwd","image/x-xwindowdump", "z","application/octet-stream", "zip","application/zip", }); /** * Maps content types to file suffixes. */ public static Map<String,String> typeToSuffix=GripCollections.addArrayToMap(new HashMap<String,String>(),new Object[]{ "application/postscript","ai", "audio/x-aiff","aif", "audio/basic","au", "application/x-troff-msvideo","avi", "application/x-bcpio","bcpio", "application/x-netcdf","cdf", "application/x-cpio","cpio", "image/x-djvu","djv", "application/x-dvi","dvi", "application/postscript","eps", "text/x-setext","etx", "image/gif","gif", "application/x-gtar","gtar", "application/x-hdf","hdf", "text/html","htm", "image/x-iw44","iw4", "image/ief","ief", "image/jpeg","jpg", "application/x-latex","latex", "application/x-troff-man","man", "application/x-troff-me","me", "message/rfc822","mime", "video/quicktime","mov", "video/mpeg","mpg", "application/x-troff-ms","ms", "video/x-sgi-movie","mv", "application/x-netcdf","nc", "application/oda","oda", "image/x-portable-bitmap","pbm", "application/pdf","pdf", "image/x-portable-graymap","pgm", "image/x-portable-anymap","pnm", "image/x-portable-pixmap","ppm", "application/postscript","ps", "video/quicktime","qt", "image/x-cmu-rast","ras", "image/x-rgb","rgb", "application/x-troff","roff", "application/rtf","rtf", "application/x-shar","shar", "audio/basic","snd", "application/x-wais-source","src", "application/x-sv4cpio","sv4cpio", "application/x-sv4crc","sv4crc", "application/x-troff","t", "application/x-tar","tar", "application/x-tex","tex", "application/x-texinfo","texi", "image/tiff","tif", "application/x-troff","tr", "text/tab-separated-values","tsv", "text/plain","txt", "application/x-ustar","ustar", "audio/x-wav","wav", "application/x-wais-source","wsrc", "image/x-xbitmap","xbm", "image/x-xpixmap","xpm", "image/x-xwindowdump","xwd", "application/zip","zip", "application/octet-stream","", }); /** Creates a new instance of FileTypes */ public FileTypes() { } /** * Gets a file suffix for the specified content type. */ public static String getSuffixForContentType(String contentType){ return typeToSuffix.get(contentType.toLowerCase()); } /** * Gets content type for the specified file suffix. */ public static String getContentTypeForSuffix(String suffix){ return suffixToType.get(suffix.toLowerCase()); } }
7,408
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
BeanShellXMLParam.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/BeanShellXMLParam.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * BeanShellXMLParam.java * * Created on 29. marraskuuta 2004, 12:16 */ package org.wandora.utils; import java.util.Iterator; import java.util.Map; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import bsh.EvalError; import bsh.Interpreter; /** * * @author olli */ public class BeanShellXMLParam implements XMLParamAware { protected Interpreter interpreter; protected String getID; /** Creates a new instance of BeanShellXMLParam */ public BeanShellXMLParam() { interpreter=new Interpreter(); getID="returnValue"; } public BeanShellXMLParam(String src,Map params) throws Exception { this(src,params,"returnValue"); } public BeanShellXMLParam(String src,Map params,String id) throws Exception { this(); Iterator iter=params.entrySet().iterator(); while(iter.hasNext()){ Map.Entry en=(Map.Entry)iter.next(); interpreter.set((String)en.getKey(),en.getValue()); } interpreter.source(src); getID=id; } public Interpreter getInterpreter(){ return interpreter; } public Object get(){ return get(getID); } public Object get(String id){ try{ return interpreter.get(id); }catch(EvalError ee){ ee.printStackTrace(); return null; } } public void xmlParamInitialize(org.w3c.dom.Element element, org.wandora.utils.XMLParamProcessor processor) { try{ NodeList nl=element.getChildNodes(); for(int i=0;i<nl.getLength();i++){ Node n=nl.item(i); if(n instanceof Element){ Element e=(Element)n; if(e.getNodeName().equals("objects")){ Map m=(Map)processor.createObject(e); Iterator iter=m.entrySet().iterator(); while(iter.hasNext()){ Map.Entry en=(Map.Entry)iter.next(); interpreter.set((String)en.getKey(),en.getValue()); } } else if(e.getNodeName().equals("source")){ String src=e.getAttribute("src"); if(src!=null && src.length()>0){ interpreter.source(src); } else{ String contents=processor.getElementContents(e); interpreter.eval(contents); } } else if(e.getNodeName().equals("id")){ getID=(String)processor.createObject(e); } } } }catch(Exception e){ e.printStackTrace(); } } }
3,737
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IteratedMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/IteratedMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wandora.utils; import static org.wandora.utils.Tuples.t2; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.wandora.utils.Tuples.T2; /** * * A Map implementation that always iterates over the entire set to find requested * items. While this is inefficient compared to a hash map, it has the advantage that * keys can be modified after they have been inserted in the map and still be found * later. In a hash map, the hash code of the key must not change after it has been * entered in the map. * * Note that while the map does not allow two entries with equal keys to be inserted * in the map, it is possible to modify one key so that it becomes equal to another * key in the map after both have been inserted in the map. The behaviour of the * map will become somewhat strange if this is done. * * @author olli */ public class IteratedMap<K,V> extends AbstractMap<K,V> { private ArrayList<T2<K,V>> data; public IteratedMap(){ data=new ArrayList<T2<K,V>>(); } public IteratedMap(Map<? extends K,? extends V> m){ this(); putAll(m); } @Override public Set<Map.Entry<K,V>> entrySet() { return new EntrySet(); } @Override public V put(K key, V value) { for(int i=0;i<data.size();i++){ T2<K,V> d = data.get(i); if(d.e1.equals(key)) { V old=d.e2; data.set(i, t2(key,value)); return old; } } data.add(t2(key,value)); return null; } private class EntrySet extends AbstractSet<Map.Entry<K,V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(); } @Override public int size() { return data.size(); } } private class EntryIterator implements Iterator<Map.Entry<K,V>> { private int nextPos=0; public boolean hasNext() { return nextPos<data.size(); } public Map.Entry<K, V> next() { return new Entry(nextPos++); } public void remove() { data.remove(--nextPos); } } private class Entry implements Map.Entry<K,V> { private int pos; public Entry(int pos){ this.pos=pos; } public K getKey() { return data.get(pos).e1; } public V getValue() { return data.get(pos).e2; } public V setValue(V value) { T2<K,V> d=data.get(pos); data.set(pos, t2(d.e1,value)); return d.e2; } } }
3,588
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PDFbox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/PDFbox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.io.File; import java.net.URL; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; /** * * @author akivela */ public class PDFbox { public static String extractTextOutOfPDF(String url) { PDDocument doc = null; try { if(url.startsWith("file:")) { doc = PDDocument.load(new File(url)); } else { doc = PDDocument.load(new URL(url).openStream()); } PDFTextStripper stripper = new PDFTextStripper(); String content = stripper.getText(doc); doc.close(); return content; } catch(Exception e) { e.printStackTrace(); } return null; } }
1,614
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MultiNetAuthenticator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/MultiNetAuthenticator.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.net.Authenticator; import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.URL; import java.util.ArrayList; /** * * @author olli */ public class MultiNetAuthenticator extends Authenticator { private static MultiNetAuthenticator instance=null; protected final ArrayList<SingleAuthenticator> authenticators=new ArrayList<SingleAuthenticator>(); public static synchronized MultiNetAuthenticator getInstance(){ if(instance!=null) return instance; else { instance=new MultiNetAuthenticator(); return instance; } } @Override protected PasswordAuthentication getPasswordAuthentication() { String host=this.getRequestingHost(); InetAddress addr=this.getRequestingSite(); int port=this.getRequestingPort(); String protocol=this.getRequestingProtocol(); String prompt=this.getRequestingPrompt(); String scheme=this.getRequestingScheme(); URL url=this.getRequestingURL(); RequestorType reqType=this.getRequestorType(); synchronized(authenticators){ for(SingleAuthenticator auth : authenticators){ PasswordAuthentication ret=auth.getPasswordAuthentication(host, addr, port, protocol, prompt, scheme, url, reqType); if(ret!=null) return ret; } } return null; } public void addAuthenticator(SingleAuthenticator auth){ synchronized(authenticators){ authenticators.add(auth); if(authenticators.size()==1) Authenticator.setDefault(this); } } public static interface SingleAuthenticator { public PasswordAuthentication getPasswordAuthentication( String host, InetAddress addr, int port, String protocol, String prompt, String scheme, URL url, RequestorType reqType); } }
3,027
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MultiHashMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/MultiHashMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * MultiHashMap.java * * Created on March 8, 2002, 6:31 PM */ package org.wandora.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; /** * 09.05.2014 AK: Commented method boolean remove(K key, V value) * 20.08.2011 AK: Commented method Collection<V> get(K key) * 11.01.2006 OL: Removed some synchronization and new TreeSet from keySet * no need for those according to specs but don't know if something * depended on them. * 06.10.2003 PH: added remove() * * @author olli */ public class MultiHashMap<K,V> extends HashMap<K,Collection<V>> { /** Creates new MultiHashMap */ public MultiHashMap() { super(); } public void addUniq(K key, V value) { if (!containsAt(key, value)) { add(key, value); } } public void add(K key, V value){ Collection<V> c = super.get(key); if(c==null){ c=new ArrayList(); c.add(value); super.put(key,c); } else{ c.add(value); } } /* public boolean remove(K key, V value) { boolean rval = false; if (containsAt(key, value)) { Collection<V> c = get(key); rval = c.remove(value); if (c.isEmpty()) super.remove(key); } return rval; } */ /* public Collection<V> get(K key){ return super.get(key); } */ public void reset() { super.clear(); } public int totalSize(){ int count=0; for(K key : keySet()){ Collection<V> c=super.get(key); if(c!=null) count+=c.size(); } return count; } public boolean containsAt(K key,V value){ Collection<V> c=get(key); if(c==null) return false; else return c.contains(value); } @Override public java.util.Set<K> keySet() { return super.keySet(); } }
2,834
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DnDBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/DnDBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wandora.utils; import java.awt.Image; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * * @author olli */ public class DnDBox { // At least Ubuntu uses this data flavor public static final DataFlavor uriListFlavor; static { DataFlavor f=null; try { f = new DataFlavor("text/uri-list; class=java.lang.String"); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } uriListFlavor=f; } public static List<File> acceptFileList(java.awt.dnd.DropTargetDropEvent e) { try { DataFlavor fileListFlavor = DataFlavor.javaFileListFlavor; DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); if(e.isDataFlavorSupported(fileListFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); java.util.List<File> files = (java.util.List<File>) tr.getTransferData(fileListFlavor); e.dropComplete(true); return files; } else if(e.isDataFlavorSupported(stringFlavor) || e.isDataFlavorSupported(uriListFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); String data = null; if(e.isDataFlavorSupported(stringFlavor)) { data = (String)tr.getTransferData(stringFlavor); } else { data = (String)tr.getTransferData(uriListFlavor); } try { String[] split = data.split("\n"); List<URI> uris = new ArrayList<>(); for(int i=0; i<split.length; i++){ try { URI uri = new URI(split[i].trim()); uris.add( uri ); } catch(Exception ex) { // Silently ignore illegal URIs. } } List<File> files = new ArrayList<File>(); for(URI uri : uris) { try{ files.add(new File(uri)); } catch(Exception exc){ // Silently ignore illegal file URIs. } } if(!files.isEmpty()) { e.dropComplete(true); } return files; } catch(Exception ex){ ex.printStackTrace(); } return new ArrayList<File>(); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } return null; } public static Image acceptImage(java.awt.dnd.DropTargetDropEvent e) { try { Transferable tr = e.getTransferable(); if(e.isDataFlavorSupported(DataFlavor.imageFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); Image image = (Image) tr.getTransferData(DataFlavor.imageFlavor); e.dropComplete(true); return image; } } catch(IOException ioe) { ioe.printStackTrace(); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } return null; } }
5,158
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CMDParamParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/CMDParamParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * CMDParamParser.java * * Created on 20. lokakuuta 2005, 21:13 * */ package org.wandora.utils; /** * * @author olli */ public class CMDParamParser { private String[] args; public CMDParamParser(String[] args){ this.args=args; } public String getLast() { if(args.length > 0) { return args[args.length-1]; } else return null; } public String get(String param){ for(int i=0;i<args.length;i++){ if(args[i].startsWith("-")){ if(args[i].substring(1).equals(param) && i+1<args.length){ return args[i+1]; } i++; } } return null; } public boolean isSet(String param){ for(int i=0;i<args.length;i++){ if(args[i].startsWith("-")){ if(args[i].substring(1).equals(param)){ return true; } } } return false; } public String get(String param,String def){ String p=get(param); if(p==null) return def; else return p; } public Object ifSet(String param,Object ifset,Object otherwise){ if(isSet(param)) return ifset; else return otherwise; } }
2,162
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XMLParamAware.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/XMLParamAware.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * XMLParamAware.java * * Created on July 5, 2004, 1:23 PM */ package org.wandora.utils; /** * Used to tag classes that are specifically designed to work well with XMLParamProcessor. * * Must have a constructor with no parameters. After constructor returns, the init method is called. * You should perform most of the initialization here, as it will be provided with the xml element (and its children) * from the xml file. You can use processor to parse the parameters inside the element (using XMLParamProcessor.crateArray * for example) or do whatever custom initialization that is necessary. The created object will be added to * the processor symbol table by the processor where necessary after the initialization returns. * * Note that the required constructor cannot be enforced in Java with interfaces so there will be no compile * time errors if you fail to provide it but implement this interface. This will however result in a run time * error when XMLParamProcessor tries to instantiate your class. * * @author olli */ public interface XMLParamAware { public void xmlParamInitialize(org.w3c.dom.Element element, org.wandora.utils.XMLParamProcessor processor); }
2,006
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CalendarDuration.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/CalendarDuration.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * CalendarDuration.java * * Created on July 17, 2003, 4:27 PM */ package org.wandora.utils; import java.util.Calendar; public class CalendarDuration { private Calendar startCalendar = Calendar.getInstance(); private Calendar endCalendar = Calendar.getInstance(); /** Creates a new instance of CalendarDuration */ public CalendarDuration() { } public CalendarDuration(Calendar start, Calendar end) { setStartCalendar(start); setEndCalendar(end); } // ------------------------------------------------------------------------- public void setStartCalendar(Calendar calendar) { this.startCalendar = calendar; } public void setEndCalendar(Calendar calendar) { this.endCalendar = calendar; } public void setStart(int year, int mon, int day, int hour, int minute, int second) { if(startCalendar == null) startCalendar = Calendar.getInstance(); startCalendar.set(year,mon,day,hour,minute,second); } public void setEnd(int year, int mon, int day, int hour, int minute, int second) { if(endCalendar == null) endCalendar = Calendar.getInstance(); endCalendar.set(year,mon,day,hour,minute,second); } public void set(String formattedDuration) { if(formattedDuration.length() > 0) { try { setStart( Integer.parseInt(formattedDuration.substring(0,4)), Integer.parseInt(formattedDuration.substring(4,6)), Integer.parseInt(formattedDuration.substring(6,8)), Integer.parseInt(formattedDuration.substring(8,10)), Integer.parseInt(formattedDuration.substring(10,12)), Integer.parseInt(formattedDuration.substring(12,14)) ); } catch (Exception e) { startCalendar = null; } try { setEnd( Integer.parseInt(formattedDuration.substring(15,19)), Integer.parseInt(formattedDuration.substring(19,21)), Integer.parseInt(formattedDuration.substring(21,23)), Integer.parseInt(formattedDuration.substring(23,25)), Integer.parseInt(formattedDuration.substring(25,27)), Integer.parseInt(formattedDuration.substring(27,29)) ); } catch (Exception e) { endCalendar = null; } } } public Calendar getStartCalendar() { return this.startCalendar; } public Calendar getEndCalendar() { return this.endCalendar; } public String getFormattedStartCalendar() { return formatCalendar(startCalendar); } public String getFormattedEndCalendar() { return formatCalendar(endCalendar); } private String formatCalendar(Calendar cal) { if(cal != null) { return "" + cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + (cal.get(Calendar.MINUTE)<10 ? "0" + cal.get(Calendar.MINUTE) : "" + cal.get(Calendar.MINUTE)) + "." + (cal.get(Calendar.SECOND)<10 ? "0" + cal.get(Calendar.SECOND) : "" + cal.get(Calendar.SECOND)); } return ""; } }
4,385
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UnicodeBOMInputStream.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/UnicodeBOMInputStream.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; /* * File: UnicodeBOMInputStream.java * Author: Gregory Pakosz. * Date: 02 - November - 2005 */ import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; /** * The <code>UnicodeBOMInputStream</code> class wraps any * <code>InputStream</code> and detects the presence of any Unicode BOM * (Byte Order Mark) at its beginning, as defined by * <a href="http://www.faqs.org/rfcs/rfc3629.html">RFC 3629 - UTF-8, a transformation format of ISO 10646</a> * * <p>The * <a href="http://www.unicode.org/unicode/faq/utf_bom.html">Unicode FAQ</a> * defines 5 types of BOMs:<ul> * <li><pre>00 00 FE FF = UTF-32, big-endian</pre></li> * <li><pre>FF FE 00 00 = UTF-32, little-endian</pre></li> * <li><pre>FE FF = UTF-16, big-endian</pre></li> * <li><pre>FF FE = UTF-16, little-endian</pre></li> * <li><pre>EF BB BF = UTF-8</pre></li> * </ul></p> * * <p>Use the {@link #getBOM()} method to know whether a BOM has been detected * or not. * </p> * <p>Use the {@link #skipBOM()} method to remove the detected BOM from the * wrapped <code>InputStream</code> object.</p> */ public class UnicodeBOMInputStream extends InputStream { /** * Type safe enumeration class that describes the different types of Unicode * BOMs. */ public static final class BOM { /** * NONE. */ public static final BOM NONE = new BOM(new byte[]{},"NONE"); /** * UTF-8 BOM (EF BB BF). */ public static final BOM UTF_8 = new BOM(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF}, "UTF-8"); /** * UTF-16, little-endian (FF FE). */ public static final BOM UTF_16_LE = new BOM(new byte[]{ (byte)0xFF, (byte)0xFE}, "UTF-16 little-endian"); /** * UTF-16, big-endian (FE FF). */ public static final BOM UTF_16_BE = new BOM(new byte[]{ (byte)0xFE, (byte)0xFF}, "UTF-16 big-endian"); /** * UTF-32, little-endian (FF FE 00 00). */ public static final BOM UTF_32_LE = new BOM(new byte[]{ (byte)0xFF, (byte)0xFE, (byte)0x00, (byte)0x00}, "UTF-32 little-endian"); /** * UTF-32, big-endian (00 00 FE FF). */ public static final BOM UTF_32_BE = new BOM(new byte[]{ (byte)0x00, (byte)0x00, (byte)0xFE, (byte)0xFF}, "UTF-32 big-endian"); /** * Returns a <code>String</code> representation of this <code>BOM</code> * value. */ public final String toString() { return description; } /** * Returns the bytes corresponding to this <code>BOM</code> value. */ public final byte[] getBytes() { final int length = bytes.length; final byte[] result = new byte[length]; // Make a defensive copy System.arraycopy(bytes,0,result,0,length); return result; } private BOM(final byte bom[], final String description) { assert(bom != null) : "invalid BOM: null is not allowed"; assert(description != null) : "invalid description: null is not allowed"; assert(description.length() != 0) : "invalid description: empty string is not allowed"; this.bytes = bom; this.description = description; } final byte bytes[]; private final String description; } // BOM /** * Constructs a new <code>UnicodeBOMInputStream</code> that wraps the * specified <code>InputStream</code>. * * @param inputStream an <code>InputStream</code>. * * @throws NullPointerException when <code>inputStream</code> is * <code>null</code>. * @throws IOException on reading from the specified <code>InputStream</code> * when trying to detect the Unicode BOM. */ public UnicodeBOMInputStream(final InputStream inputStream) throws NullPointerException, IOException { if (inputStream == null) throw new NullPointerException("invalid input stream: null is not allowed"); in = new PushbackInputStream(inputStream,4); final byte bom[] = new byte[4]; final int read = in.read(bom); switch(read) { case 4: if ((bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE) && (bom[2] == (byte)0x00) && (bom[3] == (byte)0x00)) { this.bom = BOM.UTF_32_LE; break; } else if ((bom[0] == (byte)0x00) && (bom[1] == (byte)0x00) && (bom[2] == (byte)0xFE) && (bom[3] == (byte)0xFF)) { this.bom = BOM.UTF_32_BE; break; } case 3: if ((bom[0] == (byte)0xEF) && (bom[1] == (byte)0xBB) && (bom[2] == (byte)0xBF)) { this.bom = BOM.UTF_8; break; } case 2: if ((bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE)) { this.bom = BOM.UTF_16_LE; break; } else if ((bom[0] == (byte)0xFE) && (bom[1] == (byte)0xFF)) { this.bom = BOM.UTF_16_BE; break; } default: this.bom = BOM.NONE; break; } if (read > 0) in.unread(bom,0,read); } /** * Returns the <code>BOM</code> that was detected in the wrapped * <code>InputStream</code> object. * * @return a <code>BOM</code> value. */ public final BOM getBOM() { // BOM type is immutable. return bom; } /** * Skips the <code>BOM</code> that was found in the wrapped * <code>InputStream</code> object. * * @return this <code>UnicodeBOMInputStream</code>. * * @throws IOException when trying to skip the BOM from the wrapped * <code>InputStream</code> object. */ public final synchronized UnicodeBOMInputStream skipBOM() throws IOException { if (!skipped) { in.skip(bom.bytes.length); skipped = true; } return this; } /** * {@inheritDoc} */ @Override public int read() throws IOException { return in.read(); } /** * {@inheritDoc} */ @Override public int read(final byte b[]) throws IOException, NullPointerException { return in.read(b,0,b.length); } /** * {@inheritDoc} */ @Override public int read(final byte b[], final int off, final int len) throws IOException, NullPointerException { return in.read(b,off,len); } /** * {@inheritDoc} */ @Override public long skip(final long n) throws IOException { return in.skip(n); } /** * {@inheritDoc} */ @Override public int available() throws IOException { return in.available(); } /** * {@inheritDoc} */ @Override public void close() throws IOException { in.close(); } /** * {@inheritDoc} */ @Override public synchronized void mark(final int readlimit) { in.mark(readlimit); } /** * {@inheritDoc} */ @Override public synchronized void reset() throws IOException { in.reset(); } /** * {@inheritDoc} */ @Override public boolean markSupported() { return in.markSupported(); } private final PushbackInputStream in; private final BOM bom; private boolean skipped = false; } // UnicodeBOMInputStream
9,403
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ListenerList.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ListenerList.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.wandora.utils; import static org.wandora.utils.Tuples.t2; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.wandora.utils.Tuples.T2; /** * Provides a list of objects, primarily intended for listeners, and a way to * invoke a method in all the registered listeners, that is fire an event. * Listeners can be added or removed while an event is being fired and the * listener list is being iterated. * * Changing the listener list while an event is being fired works such that * all changes are stored in a separate list which is processed after the * event firing completes. This means that all listeners that were in the * listener list at the time event firing started will receive the event even * if they are removed from the listener list. Similarly, new listeners added * during event firing will not receive the event. * * Events can be fired by providing the name of the method or a Method object * along with parameters for the method. Alternatively you can extend * this class to have separate fire methods for different events. * * This class is thread safe and no outside synchronization is needed. * * @author olli */ public class ListenerList <T> { protected final List<T> listeners; protected final List<T2<T,Boolean>> changes; protected boolean iterating; protected Class<T> cls; protected Map<String,Method> methods; protected boolean returnValues=false; public ListenerList(Class<T> cls){ this.cls=cls; listeners=new ArrayList<T>(); changes=new ArrayList<T2<T,Boolean>>(); methods=new HashMap<String,Method>(); } public int size(){ return listeners.size(); } public boolean isEmpty(){ return listeners.isEmpty(); } public boolean isReturnValues() { return returnValues; } public void setReturnValues(boolean returnValues) { this.returnValues = returnValues; } public void addListener(T l){ synchronized(listeners){ if(iterating) changes.add(t2(l,true)); else listeners.add(l); } } public void removeListener(T l){ synchronized(listeners){ if(iterating) changes.add(t2(l,false)); else listeners.remove(l); } } protected void processChanges(){ for( T2<T,Boolean> c : changes ){ if(c.e2) listeners.add(c.e1); else listeners.remove(c.e1); } changes.clear(); } public Method findMethod(String event){ synchronized(listeners){ Method m=methods.get(event); if(m==null){ if(!methods.containsKey(event)){ Method[] ms=cls.getMethods(); for(int i=0;i<ms.length;i++){ if(ms[i].getName().equals(event)) { m=ms[i]; break; } } methods.put(event,m); } } return m; } } public Object[] fireEvent(Method m,Object ... params){ return fireEventFiltered(m,null,params); } public Object[] fireEventFiltered(Method m,ListenerFilter<T> filter,Object ... params){ synchronized(listeners){ iterating=true; Object[] ret=null; if(returnValues && m.getReturnType()!=null) ret=new Object[listeners.size()]; try{ for(int i=0;i<listeners.size();i++){ T l=listeners.get(i); if(filter==null || filter.invokeListener(l)){ if(ret!=null) ret[i]=m.invoke(l,params); else m.invoke(l, params); } } } catch(IllegalAccessException iae){ throw new RuntimeException(iae); } catch(InvocationTargetException ite){ throw new RuntimeException(ite); } finally { processChanges(); iterating=false; } return ret; } } public Object[] fireEvent(String event,Object ... params){ return fireEventFiltered(event,null,params); } public Object[] fireEventFiltered(String event,ListenerFilter<T> filter,Object ... params){ Method m=findMethod(event); if(m==null) throw new RuntimeException("Trying to fire event "+event+" but method not found."); return fireEventFiltered(m,filter,params); } public void forEach(EachDelegate delegate,Object ... params) { synchronized(listeners){ iterating=true; try{ for(int i=0;i<listeners.size();i++){ T l=listeners.get(i); delegate.run(l,params); } } finally { processChanges(); iterating=false; } } } public static interface EachDelegate<T> { public void run(T listener,Object ... params); } public static interface ListenerFilter<T> { public boolean invokeListener(T listener); } }
5,577
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AdvancedHashtable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/AdvancedHashtable.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AdvancedHashtable.java * * Created on 16. joulukuuta 2004, 19:19 */ package org.wandora.utils; import java.util.Hashtable; /** * * @author akivela */ public class AdvancedHashtable extends Hashtable { private static final long serialVersionUID = 1L; /** Creates a new instance of AdvancedHashtable */ public AdvancedHashtable() { } public String gets(Object key) { try { return (String) this.get(key); } catch (Exception e) {} return ""; } }
1,371
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
IObox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/IObox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * IObox.java * * Created on July 23, 2001, 5:31 PM * Modified 15.10.2004 / ak */ package org.wandora.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.Socket; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.wandora.application.Wandora; /** * * @author akivela */ public class IObox extends java.lang.Object { /** Creates new IObox */ private IObox() { // Private } // ------------------------------------------------------------------ IO --- // ------------------------------------------------------------------------- public static String loadFile(String fname, String enc) throws FileNotFoundException, IOException { File pf = new File(fname); FileInputStream fis = new FileInputStream(pf); String result = loadFile(fis, enc); fis.close(); return result; } public static String loadFile(String fname) throws FileNotFoundException, IOException { File pf = new File(fname); FileReader pfr = new FileReader(pf); String result = loadFile(pfr); pfr.close(); return result; } public static String loadFile(File f) throws FileNotFoundException, IOException { FileReader pfr = new FileReader(f); String result = loadFile(pfr); pfr.close(); return result; } public static String loadFile(InputStream inputStream, String enc) throws IOException { InputStreamReader input = new InputStreamReader(inputStream, enc); String result = loadFile(input); input.close(); return result; } public static String loadFile(InputStreamReader input) throws IOException { StringBuilder sb = new StringBuilder(5000); int c; while((c = input.read()) != -1) { sb.append((char) c); } input.close(); return sb.toString(); } public static String loadFile(Reader input) throws IOException { StringBuilder sb = new StringBuilder(5000); int c; while((c = input.read()) != -1) { sb.append((char) c); } input.close(); return sb.toString(); } /* public static BWImage loadBWImage(FileStoreService fileSys, String fileName) { return BWImage.loadFromGif(fileSys, fileName); } public static BWImage loadBWImage(FileInputStream bfile) throws IOException, FileNotFoundException { byte[] bytes = loadBFile(bfile); InputStream is = new ByteArrayInputStream( bytes ); BWImage img = BWImage.loadFromWbmp( is ); return img; } public static byte[] loadBFile(String fname) throws IOException, FileNotFoundException { FileInputStream bfile = new FileInputStream(fname); return loadBFile(bfile); } */ /* * Note: loadBFile methods can not be used for loading operator logos nor * picture messages since these picture files tend to be compressed. * Use loadBWFile(FileSys, String) method instead. * * Note2: loadBFile methods have not been tested in real life. Expect * minor problems if used. */ public static byte[] loadBFile(InputStream inputStream) throws IOException { byte[] btable, btabletemp; boolean reading = true; int bytesRead = 0; int newBytes = 0; ArrayList<byte []> byteChunks = new ArrayList(); int chunkSize = 5000; while (reading) { btable = new byte[chunkSize]; newBytes = inputStream.read(btable); if (newBytes != -1) { byteChunks.add(btable); bytesRead = newBytes; } else { reading = false; } } // System.out.println("loadBFile bytes read: " + ((byteChunks.size()-1) * chunkSize + bytesRead) + "!"); btable = new byte[(byteChunks.size()-1) * chunkSize + bytesRead]; for(int i=0; i<byteChunks.size()-1 ; i++) { // if (debug) System.out.println("loadBFile 1: " + i + "!"); btabletemp = byteChunks.get(i); System.arraycopy(btabletemp, 0, btable, i*chunkSize, chunkSize); } btabletemp = byteChunks.get(byteChunks.size()-1); System.arraycopy(btabletemp, 0, btable, (byteChunks.size()-1) * chunkSize, bytesRead); return btable; } public static String loadResource(String resourceName) { try { URL resouceUrl = ClassLoader.getSystemResource(resourceName); String resource = IObox.doUrl(resouceUrl); return resource; } catch (Exception e) { e.printStackTrace(); } return ""; } public static void saveBFile(String fname, byte[] data) throws IOException { File pf = new File(fname); if (pf.exists()) { pf.delete(); System.out.println("Deleting previously existing file '" + fname + "' before save file operation!"); } FileOutputStream os = new FileOutputStream(fname); os.write(data); os.flush(); os.close(); System.out.println("Saving a file '" + fname + "'"); } public static void saveBFile(String fname, InputStream in) throws IOException { byte[] btable; int bytesRead = 0; int chunkSize = 5000; boolean reading = true; File pf = new File(fname); if (pf.exists()) { pf.delete(); System.out.println("Deleting previously existing file '" + fname + "' before save file operation!"); } FileOutputStream os = new FileOutputStream(fname); btable = new byte[chunkSize]; while (reading) { bytesRead = in.read(btable); if (bytesRead != -1) { os.write(btable,0 , bytesRead); } else { reading = false; } } os.flush(); os.close(); } /** * Method writes given string to a file specified by given file name. If the * file with given file name exist the file is removed before data is written. * Note that this method does not suit for binary operations. * @param fname The file name of created file. * @param data The content to be written into the file. * @throws IOException is thrown if the operation failed. */ public static void saveFile(String fname, String data) throws IOException { File pf = new File(fname); if (pf.exists()) { pf.delete(); System.out.println("Deleting previously existing file '" + fname + "' before save file operation!"); } FileWriter pfr = new FileWriter(fname); pfr.write(data, 0, data.length()); pfr.flush(); pfr.close(); System.out.println("Saving a file '" + fname + "'"); } /** * Method writes given string to a file specified by given file object. If the * file with given file name exist the file is removed before data is written. * Note that this method does not suit for binary operations. * @param pf The file where data is written.. * @param data The content to be written into the file. * @throws IOException is thrown if the operation failed. */ public static void saveFile(File pf, String data) throws IOException { if (pf.exists()) { pf.delete(); System.out.println("Deleting previously existing file '" + pf.getName() + "' before save file operation!"); } FileWriter pfr = new FileWriter(pf); pfr.write(data, 0, data.length()); pfr.flush(); pfr.close(); System.out.println("Saving a file '" + pf.getAbsolutePath() + "'"); } /** * Method deletes a local file specified by file's name. * @param fname The name of the file to be deleted. * @throws FileNotFoundException is thrown if the file was not found. * @throws IOException is thrown if the deletion failed. */ public static void deleteFile(String fname) throws FileNotFoundException, IOException { File pf = new File(fname); if (pf.exists()) { pf.delete(); System.out.println("Deleting file '" + fname + "'"); } else { System.out.println("File '" + fname + "' can not be deleted. File does not exist!"); throw new FileNotFoundException(); } } /** * Method deletes a local file specified by file's name. * @param directory The name of the directory where deleted files locate. */ public static void deleteFiles(String directory) { String[] files = getFileNames(directory, ".*", 1, 9999); for(int i=0; i<files.length; i++) { try { deleteFile(files[i]); } catch (Exception e) {} } } /** * MoveFile method renames local file. File can be tranferred into another directory. * @param sourcefile The filename of source file. * @param targetfile The filename of target file. * @throws FileNotFoundException is thrown if the source file was not found. * @throws IOException is thrown if the renaming failed. */ public static void moveFile(String sourcefile, String targetfile, boolean createTargetPath, boolean overwrite) throws FileNotFoundException, IOException { File source = new File(sourcefile); File target = new File(targetfile); if (source.exists()) { if(target.exists()) deleteFile(target.getAbsolutePath()); if(createTargetPath) createPathFor(target.getParentFile()); source.renameTo(target); System.out.println("Renaming file '" + sourcefile + "' to '" + targetfile + "'!"); } else { System.out.println("File '" + sourcefile + "' can not be renamed to '" + targetfile + "'. File does not exist!"); throw new FileNotFoundException(); } } public static void moveFile(String sourcefile, String targetfile) throws FileNotFoundException, IOException { moveFile(sourcefile, targetfile, false, false); } public static void copyFile(String sourcefile, String targetfile, boolean createTargetPath, boolean overwrite) throws FileNotFoundException, IOException, Exception { File source = new File(sourcefile); File target = new File(targetfile); if (source.exists()) { if(target.exists() && overwrite) deleteFile(target.getAbsolutePath()); if(createTargetPath) createPathFor(target.getParentFile()); //InputStream in, OutputStream out moveData(new FileInputStream(source), new FileOutputStream(target)); System.out.println("Copying file '" + sourcefile + "' to '" + targetfile + "'!"); } else { System.out.println("File '" + sourcefile + "' can not be renamed to '" + targetfile + "'. File does not exist!"); throw new FileNotFoundException(); } } public static void copyFile(String sourcefile, String targetfile) throws FileNotFoundException, IOException, Exception { copyFile(sourcefile, targetfile, false, false); } public static void createPathFor(File dir) { if(dir != null) { dir.mkdirs(); } } //---------------------------------------------------------------------------- public static File[] getFiles(String fileName) { return hashSetToFileArray(getFilesAsHash(fileName)); } public static File[] getFiles(String fileName, String fileMask, int depth, int space) { return hashSetToFileArray(getFilesAsHash(fileName, fileMask, depth, space)); } public static String[] getFileNames(String fileName) { return hashSetToStringArray(getFilesAsHash(fileName)); } public static String[] getFileNames(String fileName, String fileMask, int depth, int space) { return hashSetToStringArray(getFilesAsHash(fileName, fileMask, depth, space)); } public static HashSet<String> getFilesAsHash(String fileName) { return getFilesAsHash(fileName, ".*", 10, 10000); } public static HashSet<String> getFilesAsHash(String fileName, String fileMask, int depth, int space) { Pattern p = null; try { p = Pattern.compile(fileMask); return getFilesAsHash(fileName, p, new ArrayList(), depth, space); } catch(Exception e) { e.printStackTrace(); } return new LinkedHashSet(); } public static HashSet<String> getFilesAsHash(String fileName, Pattern fileMask, Collection visited, int depth, int space) { HashSet files = new LinkedHashSet(); if(depth >= 0) { if (space >= 0) { File file = new File(fileName); if (file.exists()) { if(file.isDirectory()) { if(!visited.contains(fileName)) { visited.add(fileName); try { // System.out.println("a dir found: " + fileName); String[] directoryFiles = file.list(); for(int i=0; i<directoryFiles.length; i++) { // System.out.println(" trying: " + File.separator + directoryFiles[i]); files.addAll(getFilesAsHash(fileName + File.separator + directoryFiles[i], fileMask, visited, depth-1, space-files.size())); } } catch (Exception e) { e.printStackTrace(); } } } else { try { if(fileMask == null) { files.add(fileName); } else { Matcher m = fileMask.matcher(fileName); if(m.matches()) { files.add(fileName); // System.out.println("matching file found: " + fileName); } } } catch (Exception e) { e.printStackTrace(); } } } } else { System.out.println("Maximum file number exceeded! Accepting no more files in getFiles!"); } } else { //System.out.println("Maximum browse depth exceeded!"); } return files; } // ------------------------------------------------------------------------- public static int countFiles(String fileName, String fileMask, int depth, int space) { Pattern p = null; try { p = Pattern.compile(fileMask); return countFiles(fileName, p, new ArrayList(), depth, space); } catch(Exception e) { e.printStackTrace(); } return -1; } public static int countFiles(String fileName, Pattern fileMask, Collection visited, int depth, int space) { int fileCount = 0; if(depth >= 0) { if (space >= 0) { File file = new File(fileName); if (file.exists()) { if(file.isDirectory()) { if(!visited.contains(fileName)) { visited.add(fileName); //System.out.println("a dir found: " + fileName); String[] directoryFiles = file.list(); for(int i=0; i<directoryFiles.length; i++) { //System.out.println(" trying: " + File.separator + directoryFiles[i]); fileCount = fileCount + countFiles(fileName + File.separator + directoryFiles[i], fileMask, visited, depth-1, space-fileCount); } } } else { //System.out.println("a file found: " + fileName); try { if(fileMask == null) { fileCount++; } else { Matcher m = fileMask.matcher(fileName); if(m.matches()) { fileCount++; } } } catch (Exception e) { e.printStackTrace(); } } } } else { System.out.println("Maximum file number exceeded! Accepting no more files in countFiles!"); } } else { //System.out.println("Maximum browse depth exceeded!"); } return fileCount; } // ------------------------------------------------------------------------- // ----------------------------------------------------------- FIND FILE --- // ------------------------------------------------------------------------- public static String findFile(String fileName, String fileMask, int depth) { Pattern p = null; try { p = Pattern.compile(fileMask); return findFile(fileName, p, new ArrayList(), depth); } catch(Exception e) { e.printStackTrace(); } return null; } public static String findFile(String root, Pattern fileMask, Collection visited, int depth) { String foundFile = null; if(depth >= 0) { File file = new File(root); if(file.exists()) { if(file.isDirectory()) { if(!visited.contains(root)) { try { visited.add(root); //System.out.println("a dir found: " + root); String[] directoryFiles = file.list(); String dir = null; for(int i=0; i<directoryFiles.length && foundFile == null; i++) { dir = root + File.separator + directoryFiles[i]; //System.out.println(" trying: " + File.separator + directoryFiles[i]); foundFile = findFile(dir, fileMask, visited, depth-1); } } catch (Exception e) { e.printStackTrace(); } } } else { try { if(fileMask != null) { Matcher m = fileMask.matcher(root); if(m.matches()) { foundFile = root; System.out.println("matching file found: " + foundFile); } } } catch (Exception e) { e.printStackTrace(); } } } } else { System.out.println("Maximum browse depth exceeded!"); } return foundFile; } // ------------------------------------------------------------ FIND URI --- public static String findURI(String fileName, String fileMask, int depth) { Pattern p = null; try { p = Pattern.compile(fileMask); return findFile(fileName, p, new ArrayList(), depth); } catch(Exception e) { e.printStackTrace(); } return null; } public static String findURI(String root, Pattern fileMask, Collection visited, int depth) { String foundFile = null; if(depth >= 0) { File file = new File(root); if(file.exists()) { if(file.isDirectory()) { if(!visited.contains(root)) { try { visited.add(root); //System.out.println("a dir found: " + root); String[] directoryFiles = file.list(); String dir = null; for(int i=0; i<directoryFiles.length && foundFile == null; i++) { dir = root + File.separator + directoryFiles[i]; //System.out.println(" trying: " + File.separator + directoryFiles[i]); foundFile = findFile(dir, fileMask, visited, depth-1); } } catch (Exception e) { e.printStackTrace(); } } } else { try { if(fileMask != null) { Matcher m = fileMask.matcher(root); if(m.matches()) { foundFile = root; System.out.println("matching file found: " + foundFile); } } } catch (Exception e) { e.printStackTrace(); } } } } else { System.out.println("Maximum browse depth exceeded!"); } return foundFile; } //-------------------------------------------------------------------------- public static long getModificationTime(URL url) { try { URLConnection connection = url.openConnection(); Wandora.initUrlConnection(connection); //System.out.println("LAST MOD:" + connection.getLastModified()); return connection.getLastModified(); } catch (Exception e) {} return 0; } public static long getModificationTime(String fname) { try { File pf = new File(fname); if (pf.exists()) { return pf.lastModified(); } } catch (Exception e) {} return 0; } public static String getYoungestFile(String baseName, String fileMask) { return getOldestOrYoungestFile(baseName, fileMask, false); } public static String getOldestFile(String baseName, String fileMask) { return getOldestOrYoungestFile(baseName, fileMask, true); } public static String getOldestOrYoungestFile(String baseName, String fileMask, boolean oldest) { Pattern p = null; try { p = Pattern.compile(fileMask); return getOldestOrYoungestFile(baseName, p, oldest); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getOldestOrYoungestFile(String baseName, Pattern fileMask, boolean oldest) { String requestedFile = null; long requestedFileMod; long fileMod; String fileName = null; if(oldest) requestedFileMod = Long.MAX_VALUE; else requestedFileMod = 0; File file = new File(baseName); if (file.exists()) { if(file.isDirectory()) { System.out.println("a dir found: " + fileName); String[] directoryFiles = file.list(); for(int i=0; i<directoryFiles.length; i++) { fileName = baseName + File.separator + directoryFiles[i]; System.out.println(" trying: " + baseName + File.separator + directoryFiles[i]); try { if(fileMask == null || fileMask.matcher(fileName).matches()) { fileMod = getModificationTime(fileName); if(oldest) { if(fileMod < requestedFileMod) { System.out.println(" oldest found: " + directoryFiles[i]); requestedFileMod = fileMod; requestedFile = fileName; } } else { if(fileMod > requestedFileMod) { System.out.println(" youngest found: " + directoryFiles[i]); requestedFileMod = fileMod; requestedFile = fileName; } } } } catch (Exception e) { e.printStackTrace(); } } } else { //System.out.println("a file found: " + fileName); if(fileMask.matcher(fileName).matches()) { requestedFile = baseName; } } } return requestedFile; } //---------------------------------------------------------------------------- /** * Method executes an url (with given data) and returns the string url generated. * Method can be used to download web data or execute cgi or similar programs * addressable by url. Method uses deprecated methods - to be updated. * * @param url The url executed. * @param data The string transferred to the url during execution. * @param ctype The string representing content type used during execution. * @return The string url execution generated. */ public static String doUrl(URL url, String data, String ctype, String method) throws IOException { StringBuilder sb = new StringBuilder(5000); if (url != null) { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoInput(true); con.setUseCaches(false); if(method != null && con instanceof HttpURLConnection) { ((HttpURLConnection) con).setRequestMethod(method); //System.out.println("****** Setting HTTP request method to "+method); } if(ctype != null) { con.setRequestProperty("Content-type", ctype); } if(data != null && data.length() > 0) { con.setRequestProperty("Content-length", data.length() + ""); con.setDoOutput(true); PrintWriter out = new PrintWriter(con.getOutputStream()); out.print(data); out.flush(); out.close(); } //DataInputStream in = new DataInputStream(con.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String s; while ((s = in.readLine()) != null) { sb.append(s); if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n"); } in.close(); } return sb.toString(); } public static String doUrl(URL url) throws IOException { return doUrl(url, "", "text/plain", null); } public static String doUrl(URL url, String data) throws IOException { return doUrl(url, data, "text/plain", null); } public static String doUrl(URL url, String data, String ctype) throws IOException { return doUrl(url, data, ctype, null); } public static void moveUrl(URL sourceUrl, File targetFile) throws Exception { moveUrl(sourceUrl, targetFile, null, null, true); } public static void moveUrl(URL sourceUrl, File targetFile, String user, String password, boolean deleteFile) throws Exception { String protocol = sourceUrl.getProtocol(); if("file".equals(protocol)) { String filename = sourceUrl.toExternalForm().substring(6); FileInputStream in = new FileInputStream(new File(filename)); FileOutputStream out = new FileOutputStream(targetFile); moveData(in, out); if(deleteFile) deleteFile(filename); } else { URLConnection con = sourceUrl.openConnection(); Wandora.initUrlConnection(con); con.setUseCaches(false); if(user != null && password != null) { String userPassword = user + ":" + password; // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); String encodedUserPassword = Base64.encodeBytes(userPassword.getBytes()); con.setRequestProperty ("Authorization", "Basic " + encodedUserPassword); } InputStream in = con.getInputStream(); FileOutputStream out = new FileOutputStream(targetFile); moveData(in, out); } } public static void moveData(InputStream in, OutputStream out) throws Exception { byte[] data = new byte[8000]; int l = 0; while ((l = in.read(data)) > -1) { out.write(data, 0, l); } in.close(); out.flush(); out.close(); } public static boolean urlExists(URL url) { return urlExists(url, null); } public static boolean urlExists(URL url, HttpAuthorizer httpAuthorizer) { if (url != null) { String protocol = url.getProtocol(); if("file".equals(protocol)) { try { String fname = url.toExternalForm().substring(5); while(fname.startsWith("/")) fname = fname.substring(1); File pf = new File(fname); if (pf.exists()) { return true; } } catch (Exception e) { e.printStackTrace(); } } else { InputStream in = null; try { URLConnection connection = null; if(httpAuthorizer != null) { connection = httpAuthorizer.getAuthorizedAccess(url); } else { connection = url.openConnection(); Wandora.initUrlConnection(connection); } in = connection.getInputStream(); int b = in.read(); in.close(); return true; } catch (Exception e) { e.printStackTrace(); } finally { try { if(in != null) in.close(); } catch (Exception e) {} } } } return false; } public static boolean isAuthException(Exception e) { if(e instanceof java.io.IOException) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); if(sw.toString().indexOf("Server returned HTTP response code: 401") != -1) return true; } catch (Exception ex) { ex.printStackTrace(); } } return false; } // ------------------------------------------------------------------------- // ----------------------------------------------------- FILE EXTENSIONS --- // ------------------------------------------------------------------------- public static File forceFileExtension(File candidate, String extension) { if(!candidate.exists()) { if(!extension.startsWith(".")) extension = "." + extension; candidate = new File(getFileWithoutExtension(candidate) + extension); } return candidate; } public static File addFileExtension(File candidate, String extension) { if(!candidate.exists()) { String oldExtension = getFileExtension(candidate); if(oldExtension == null || oldExtension.length()<1) { if(!extension.startsWith(".")) extension = "." + extension; candidate = new File(candidate.getPath() + extension); } } return candidate; } public static String getFileExtension(File file) { String extension = null; if(file != null) { String filename = file.getName(); int i = filename.lastIndexOf('.'); if(i > 0) { extension = filename.substring(i); } } return extension; } public static String getFileWithoutExtension(File file) { String filenameWithoutExtension = file.getPath(); if(filenameWithoutExtension != null) { int i = filenameWithoutExtension.lastIndexOf('.'); int j = filenameWithoutExtension.lastIndexOf('/'); if(i > 0 && i > j) { filenameWithoutExtension = filenameWithoutExtension.substring(0, i); } } return filenameWithoutExtension; } // ------------------------------------------------------------------------- // -- Next are from Http tool of com.gripstudios.platform.tools.HttpTools -- // ------------------------------------------------------------------------- private static final int BLOCK_LENGTH = 8192; /** * Fetches the contents of the specified url. * @param url URL to be fetched * @return the returned contents of the url */ public static byte[] fetchUrl( URL url ) { if( url!=null ) { try { URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoOutput(false); con.setDoInput(true); con.setUseCaches(false); con.connect(); DataInputStream inS = new DataInputStream(con.getInputStream()); Vector bufs = new Vector(); Vector lengths = new Vector(); int length = 0; for(;;) { byte[] buf = new byte[BLOCK_LENGTH]; int readBytes = inS.read(buf); // System.out.println("+"+readBytes+"b"); if( readBytes==-1 ) { break; } length += readBytes; bufs.addElement(buf); lengths.addElement(Integer.valueOf(readBytes)); } inS.close(); byte[] data = new byte[length]; int pos = 0; for( int el=0;el<bufs.size();el++ ) { int len = ((Integer)lengths.elementAt(el)).intValue(); System.arraycopy( bufs.elementAt(el),0,data,pos,len ); pos += len; } return data; } catch( Exception e ) { System.out.println( "ERR Caught: "+e.toString() ); } return null; } return null; } public static void executeUrlCall( URL url ) { StringBuffer sb = new StringBuffer(5000); if (url != null) { try { System.out.println( url.toString() ); URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoOutput(false); con.setDoInput(true); con.setUseCaches(false); con.connect(); // BufferedWriter outS = new BufferedWriter( new OutputStreamWriter(con.getOutputStream()) ); // outS.close(); DataInputStream inS = new DataInputStream(con.getInputStream()); byte[] buf = new byte[1024]; while( inS.read(buf)!=-1 ) {} inS.close(); } catch( Exception e ) { System.out.println( "ERR Caught: "+e.toString() ); } } } public static String executeUrlPost( URL url, byte[] data, String ctype, boolean waitForResponse ) { return executeUrlPost(url, data, ctype, waitForResponse, null); } public static String executeUrlPost( URL url, byte[] data, String ctype, boolean waitForResponse, java.util.Hashtable params ) { StringBuilder sb = new StringBuilder(5000); if (url != null) { try { System.out.println( url.toString() ); URLConnection con = url.openConnection(); Wandora.initUrlConnection(con); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type",ctype); if (params!=null) { for (java.util.Enumeration e = params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); String value = (String) params.get(key); con.setRequestProperty(key, value); } } OutputStream outS = con.getOutputStream(); outS.write(data); outS.flush(); outS.close(); con.connect(); if( waitForResponse ) { DataInputStream inS = new DataInputStream(con.getInputStream()); byte[] buf = new byte[1024]; while( inS.read(buf)!=-1 ) {} inS.close(); // String reply = new String(buf); } return "OK"; } catch( Exception e ) { return e.toString(); } } return "No url!"; } public static String executeSocketUrlCall( URL url ) { if( null==url ) { return "No url!"; } try { int port = url.getPort(); if( port==-1 ) port = 80; Socket s = new Socket( url.getHost(), port ); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); String host = url.getProtocol()+"://"+url.getHost()+":"+port; String encoded = url.getPath()+"?"+url.getQuery(); String header = "GET " + encoded + " HTTP/1.1\r\n"; // System.out.println( header ); bw.write( header ); bw.write( "\r\n" ); bw.flush(); // TODO could parse return code and return it BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream() ) ); if ( br.ready() ) { String line = null; while ( (line = br.readLine()) != null ) { } } } catch( Exception e ) { return e.toString(); } return "OK"; } // ------------------------------------------------------------------------- public static String[] hashSetToStringArray(HashSet s) { String[] strings = null; if(s != null) { if(s.size() > 0) { strings = new String[s.size()]; int i = 0; for(Object o : s) { try { strings[i] = (String) o; } catch (Exception e) { System.out.println("Object not a String in hashSetToStringArray. Skipping!"); strings[i] = ""; } i++; } } else { strings = new String[0]; } } return strings; } public static File[] hashSetToFileArray(HashSet s) { File[] files = null; if(s != null) { if(s.size() > 0) { files = new File[s.size()]; int i = 0; for(Object o : s) { try { files[i] = new File((String) o); } catch (Exception e) { System.out.println("Object not a File in hashSetToFileArray. Skipping!"); files[i] = null; } i++; } } else { files = new File[0]; } } return files; } public static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; public static void disableHTTPSCertificateValidation() { // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } } public static String getFileFromURI(URI uri){ return getFileFromURL(uri.toString()); } public static String getFileFromURL(URL url){ return getFileFromURL(url.toExternalForm()); } public static String getFileFromURL(String url){ if(url.startsWith("file:")){ url=url.substring("file:".length()); while(url.startsWith("//")) url=url.substring(1); try{ return URLDecoder.decode(url, "UTF-8"); }catch(UnsupportedEncodingException uee){uee.printStackTrace();return null;} } else return null; } }
45,933
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CSVParser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/CSVParser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PushbackReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * * @author olli */ public class CSVParser { private char valueSeparator=','; private char lineSeparator='\n'; private char stringChar='"'; private String encoding = "UTF-8"; public CSVParser(){ } public Table parse(String filename) throws IOException { return parse(new File(filename)); } public Table parse(String filename, String encoding) throws IOException { return parse(new File(filename),encoding); } public Table parse(File f) throws IOException { return parse(new FileInputStream(f)); } public Table parse(File f, String encoding) throws IOException { return parse(new FileInputStream(f), encoding); } public Table parse(InputStream inRaw) throws IOException { return parse(inRaw, encoding); } public Table parse(InputStream inRaw, String encoding) throws IOException { Table ret=new Table(); PushbackReader in=new PushbackReader(new InputStreamReader(inRaw,encoding),20); Row row=null; while( (row=readLine(in))!=null ){ ret.add(row); } return ret; } private Row readLine(PushbackReader in) throws IOException { Row ret=new Row(); while(true){ int c=in.read(); if(c<0) { if(ret.size()>0) return ret; else return null; } else in.unread(c); Object v=readValue(in); ret.add(v); boolean next=readValueSeparator(in); if(!next) break; } return ret; } private Object readValue(PushbackReader in) throws IOException { readWhitespace(in); while(true){ int c=in.read(); if(c==valueSeparator || c==lineSeparator) { in.unread(c); return null; } if(c<0){ return null; } else if(c==stringChar){ in.unread(c); return parseString(in); } else { in.unread(c); return parseNumberOrDate(in); } } } private boolean readValueSeparator(PushbackReader in) throws IOException { readWhitespace(in); while(true) { int c=in.read(); if(c==valueSeparator) return true; else if(c==lineSeparator || c<0) return false; else { throw new RuntimeException("Error parsing CSV file"); } } } private Object parseNumberOrDate(PushbackReader in) throws IOException { readWhitespace(in); StringBuilder sb=new StringBuilder(); while(true) { int c=in.read(); if(c==valueSeparator || c==lineSeparator || c<0) { if(c>=0) in.unread(c); break; } else sb.append((char)c); } String s=sb.toString().trim(); try { int i=Integer.parseInt(s); return i; } catch(NumberFormatException nfe) { try { double d=Double.parseDouble(s); return d; } catch(NumberFormatException nfe2) { try { return parseDate(s); } catch(Exception ex) { return s; // FINALLY WHEN EVERYTHING ELSE FAILS RETURN THE STRING AS A VALUE } } } } private SimpleDateFormat[] dateFormats={ new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("MM/dd/yyyy"), new SimpleDateFormat("dd.MM.yyyy") }; private Date parseDate(String s) throws IOException { Date d=null; for(SimpleDateFormat df : dateFormats) { try { d=df.parse(s); break; } catch(ParseException pe){ continue; } } if(d==null) { throw new RuntimeException("Error parsing CSV file"); } else return d; } private String parseIntPart(PushbackReader in) throws IOException { StringBuilder sb=new StringBuilder(); while(true){ int c=in.read(); if(c>='0' && c<='9'){ sb.append((char)c); } else { if(c>=0) in.unread(c); if(sb.length()==0) return null; else return sb.toString(); } } } private String parseString(PushbackReader in) throws IOException { readWhitespace(in); int c=in.read(); if(c!=stringChar) throw new RuntimeException("Error parsing CSV file"); StringBuilder sb=new StringBuilder(); while(true){ c=in.read(); if(c<0) throw new RuntimeException("Error parsing CSV file"); else if(c == stringChar) { int c2=in.read(); if(c2==stringChar){ sb.append((char)stringChar); } else { if(c2>=0) in.unread(c2); return sb.toString(); } } else { sb.append((char)c); } } } private void readWhitespace(PushbackReader in) throws IOException { while(true){ int c=in.read(); if(c<0) return; else if(c!=lineSeparator && Character.isWhitespace(c)) continue; else { in.unread(c); return; } } } public static class Row extends ArrayList<Object>{} public static class Table extends ArrayList<Row>{} /* public static void main(String[] args) throws Exception { InputStream in=System.in; // InputStream in=new FileInputStream("Strindberg_lahtenyt_kv_1.csv"); Table t=new CSVParser().parse(in); System.out.println("Parsed "+t.size()+" rows"); for(Row r : t){ for(Object o : r){ if(o==null) System.out.print("null,"); else System.out.print(o.toString()+","); } System.out.println(); } } */ // ------------------------------------------------------------------------- public void setValueSeparator(char c) { valueSeparator=c; } public void setLineSeparator(char c) { lineSeparator=c; } public void setStringCharacter(char c) { stringChar=c; } public void setEncoding(String e) { encoding = e; } public char getValueSeparator() { return valueSeparator; } public char getLineSeparator() { return lineSeparator; } public char getStringCharacter() { return stringChar; } public String getEncoding() { return encoding; } }
8,213
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Base64.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Base64.java
package org.wandora.utils; /** * Encodes and decodes to and from Base64 notation. * * <p>(This class has been developed outside Grip Studios. The original author * has placed the code in public domain. Following is the original documentation * of the class.)</p> * * <p> * Change Log: * </p> * <ul> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/xmlizable">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.0 */ public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding. */ public final static int ENCODE = 1; /** Specify decoding. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed. */ public final static int GZIP = 2; /** Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES = 8; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] ALPHABET; private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").getBytes( PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = _NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * * @param threeBytes the array to convert * @return four byte array in Base64 notation. * @since 1.3 */ private static byte[] encode3to4( byte[] threeBytes ) { return encode3to4( threeBytes, 3 ); } // end encodeToBytes /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.3 */ private static byte[] encode3to4( byte[] threeBytes, int numSigBytes ) { byte[] dest = new byte[4]; encode3to4( threeBytes, 0, numSigBytes, dest, 0 ); return dest; } /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0 ); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; java.util.zip.GZIPOutputStream gzos = null; // Isolate options int gzip = (options & GZIP); int dontBreakLines = (options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); // GZip? if( gzip == GZIP ) { gzos = new java.util.zip.GZIPOutputStream( b64os ); oos = new java.io.ObjectOutputStream( gzos ); } // end if: gzip else oos = new java.io.ObjectOutputStream( b64os ); oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @since 1.4 */ public static String encodeBytes( byte[] source ) { return encodeBytes( source, 0, source.length, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) { // Isolate options int dontBreakLines = ( options & DONT_BREAK_LINES ); int gzip = ( options & GZIP ); // Compress? if( gzip == GZIP ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; int len43 = len * 4 / 3; byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e ); e += 4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String( outBuff, 0, e, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); } // end catch } // end else: don't compress } // end encodeBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes the first four bytes of array <var>fourBytes</var> * and returns an array up to three bytes long with the * decoded values. * * @param fourBytes the array with Base64 content * @return array with decoded values * @since 1.3 */ private static byte[] decode4to3( byte[] fourBytes ) { byte[] outBuff1 = new byte[3]; int count = decode4to3( fourBytes, 0, outBuff1, 0 ); byte[] outBuff2 = new byte[ count ]; for( int i = 0; i < count; i++ ) outBuff2[i] = outBuff1[i]; return outBuff2; } /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { try{ // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; } //e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len ) { int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for( i = off; i < off+len; i++ ) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ sbiCrop ]; if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode( String s ) { byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( bytes.length >= 2 ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( bytes != null && // In case decoding returned null bytes.length >= 4 && // Don't want to get ArrayIndexOutOfBounds exception java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject( String encodedObject ) { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); ois = new java.io.ObjectInputStream( bais ); obj = ois.readObject(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); obj = null; } // end catch catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); obj = null; } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A Base64.InputStream will read data from another * java.io.InputStream, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @see java.io.FilterInputStream * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private int options; // Options specified private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a Base64.InputStream in DECODE mode. * * @param in the java.io.InputStream from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a Base64.InputStream in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the java.io.InputStream from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.options = options; this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.breakLines = breakLines; this.encode = encode; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { try { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; } // end catch } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0 ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) break; // Reads a -1 if end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0 ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ) return -1; if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); //if( b < 0 && i == 0 ) // return -1; if( b >= 0 ) dest[off + i] = (byte)b; else if( i == 0 ) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A Base64.OutputStream will write data to another * java.io.OutputStream, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @see java.io.FilterOutputStream * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private int options; private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a Base64.OutputStream in ENCODE mode. * * @param out the java.io.OutputStream to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a Base64.OutputStream in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the java.io.OutputStream to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.options = options; this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to encode. { out.write( encode3to4( b4, buffer, bufferLength ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to output. { int len = Base64.decode4to3( buffer, 0, b4, 0 ); out.write( b4, 0, len ); //out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64
50,036
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OpenOfficeBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/OpenOfficeBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.utils; import java.io.File; import java.io.InputStream; import java.net.URL; import org.odftoolkit.simple.ChartDocument; import org.odftoolkit.simple.Document; import org.odftoolkit.simple.GraphicsDocument; import org.odftoolkit.simple.PresentationDocument; import org.odftoolkit.simple.SpreadsheetDocument; import org.odftoolkit.simple.TextDocument; import org.odftoolkit.simple.table.Cell; import org.odftoolkit.simple.table.Row; import org.odftoolkit.simple.table.Table; /** * Simple collection of methods used to access and extract Open Office * documents. * * @author akivela */ public class OpenOfficeBox { public static String getText(URL url) { try { return getText(Document.loadDocument(url.openStream())); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(File file) { try { return getText(Document.loadDocument(file)); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(InputStream is) { try { return getText(Document.loadDocument(is)); } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(Document document) { if(document instanceof TextDocument) { return getText((TextDocument) document); } else if(document instanceof SpreadsheetDocument) { return getText((SpreadsheetDocument) document); } else if(document instanceof PresentationDocument) { return getText((PresentationDocument) document); } else if(document instanceof ChartDocument) { return getText((ChartDocument) document); } else if(document instanceof GraphicsDocument) { return getText((GraphicsDocument) document); } return null; } public static String getText(ChartDocument chartDocument) { try { String text = chartDocument.getContentRoot().getTextContent(); return text; } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(GraphicsDocument gfxDocument) { try { String text = gfxDocument.getContentRoot().getTextContent(); return text; } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(PresentationDocument presentationDocument) { try { String text = presentationDocument.getContentRoot().getTextContent(); return text; } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(TextDocument textDocument) { try { String text = textDocument.getContentRoot().getTextContent(); return text; } catch(Exception e) { e.printStackTrace(); } return null; } public static String getText(SpreadsheetDocument spreadsheetDocument) { try { StringBuilder stringBuilder = new StringBuilder(""); int sheetCount = spreadsheetDocument.getSheetCount(); for(int i=0; i<sheetCount; i++) { Table sheet = spreadsheetDocument.getSheetByIndex(i); int rowCount = sheet.getRowCount(); for(int y=0; y<rowCount; y++) { Row row = sheet.getRowByIndex(y); int cellCount = row.getCellCount(); for(int x=0; x<cellCount; x++) { Cell cell = row.getCellByIndex(x); String value = cell.getStringValue(); stringBuilder.append(value); stringBuilder.append("\t"); } stringBuilder.append("\n"); } stringBuilder.append("\n\n"); } return stringBuilder.toString(); } catch(Exception e) { e.printStackTrace(); } return null; } }
5,241
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Delegate.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Delegate.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Delegate.java * * Created on 7. tammikuuta 2005, 13:31 */ package org.wandora.utils; /** * <p> * Delegate is a function wrapped in an Object. Normally you will want to make * an anonymous inner class implementing Delegate and pass that object somewhere. * Delegate can be used as a generic listener (the delegate is invoked on an * event) or some kind of other handler. If you need to use more than one * parameter, you can use the com.gripstudios.utils.Tuples library. * </p><p> * If your delegate doesn't return a value, you can set it to return Object and * then just return null or you can set the return value to Delegate.Void and * return Delegate.VOID to make it clear that the return value means nothing. * </p><p> * Using Delegate class you can use some programming techniques readily available * in functional programming languages allthough the syntax in Java becomes * somewhat inconvenient. * </p> * @author olli */ public interface Delegate<R,P> { public R invoke(P param); public static final class Void{ private Void(){} } public static final Void VOID=new Void(); }
1,943
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AbortableProgressDialog.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/AbortableProgressDialog.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * CopyProgressDialog.java * * Created on 27.6.2008, 14:08 */ package org.wandora.utils; /** * * @author anttirt */ public class AbortableProgressDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Runnable abortProc; private Abortable.Status status; private double ratio; /** Creates new form AbortableProgressDialog */ public AbortableProgressDialog(java.awt.Frame parent, boolean modal, Runnable abortProc, String title) { super(parent, modal); this.abortProc = abortProc; status = Abortable.Status.InProgress; ratio = 0.0; initComponents(); this.setTitle(title); this.setSize(320, 160); jProgressBar1.setMaximum(1000); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; wandoraButton1 = new org.wandora.application.gui.simple.SimpleButton(); msgLabel = new org.wandora.application.gui.simple.SimpleLabel(); jProgressBar1 = new javax.swing.JProgressBar(); closeBtn = new org.wandora.application.gui.simple.SimpleButton(); wandoraButton1.setText("wandoraButton1"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(new java.awt.GridBagLayout()); msgLabel.setText("File copy progress:"); msgLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 10); getContentPane().add(msgLabel, gridBagConstraints); jProgressBar1.setMinimumSize(new java.awt.Dimension(300, 16)); jProgressBar1.setPreferredSize(new java.awt.Dimension(300, 16)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10); getContentPane().add(jProgressBar1, gridBagConstraints); closeBtn.setText("Abort"); closeBtn.setMaximumSize(new java.awt.Dimension(70, 23)); closeBtn.setMinimumSize(new java.awt.Dimension(70, 23)); closeBtn.setPreferredSize(new java.awt.Dimension(70, 23)); closeBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeBtnActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 7, 10); getContentPane().add(closeBtn, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents public void progress(double ratio, Abortable.Status status, String message) { this.ratio = ratio; this.status = status; msgLabel.setText("<html><body><p>" + message + "</p></body></html>"); jProgressBar1.setValue((int)(ratio * 1000)); switch(status) { case InProgress: break; case Success: closeBtn.setText("OK"); break; case Failure: closeBtn.setText("OK"); break; } } private void closeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeBtnActionPerformed switch(status) { case InProgress: if(abortProc != null) abortProc.run(); break; case Success: break; case Failure: break; } this.setVisible(false); }//GEN-LAST:event_closeBtnActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* java.awt.EventQueue.invokeLater(new Runnable() { public void run() { OperationProgressDialog dialog = new OperationProgressDialog(new javax.swing.JFrame(), true, null); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); */ } // Variables declaration - do not modify//GEN-BEGIN:variables private org.wandora.application.gui.simple.SimpleButton closeBtn; private javax.swing.JProgressBar jProgressBar1; private org.wandora.application.gui.simple.SimpleLabel msgLabel; private org.wandora.application.gui.simple.SimpleButton wandoraButton1; // End of variables declaration//GEN-END:variables }
6,313
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Tuples.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Tuples.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Tuples.java * * Created on 4. tammikuuta 2005, 14:46 */ package org.wandora.utils; /** * <p> * A Tuple library to make it easy to return two or more values from a method. * Requires Java 1.5. To use do something like * <code><pre> * import static com.gripstudios.utils.Tuples.*; * ... * T2&lt;Integer,String> foo(int x,int y){ * return t2(y,new String(x)); * } * ... * </pre></code> * Note that this is typesafe where returning an Object[] is not. Note that it * is always a good idea to consider making a real class for the return value. * Especially if you need a tuple of more than 4 values (only T2,T3 and T4 are * provided in this class) you probably should make it a real class. * </p> * <p> * The Tuple classes override equals to check the equality for each element * of the tuples respectively. hashCode is also overridden so Tuples can * safely be used in hashMaps. You may put nulls in tuples. * </p> * <p> * Note that tuples are immutable, you can't change the elements in them. * Instead create a new tuple, for example * <code><pre> * T2&lt;String,Integer> a=t2("aaa",2); * ... * a=t2(a.e1,a.e2+1); * </pre></code> * </p> * <p> * Note that t2("",new Vector()) will create a T2<String,new Vector()> rather than * T2<String,Collection>. If you want the second element to be a Collection you will * have to cast the parameter: * <code>t2(String,(Collection)new Vector())</code> or * <code>t2(String,(Collection&lt;Integer>)new Vector())</code> * to be more specific. * </p> * * @author olli */ public class Tuples { private Tuples() {} private static boolean e(Object o1,Object o2){ return (o1==null?o2==null:o1.equals(o2)); } public static class T2<E1,E2>{ public final E1 e1; public final E2 e2; public T2(final E1 e1,final E2 e2){ this.e1=e1; this.e2=e2; } @Override public boolean equals(Object obj){ if(obj instanceof T2){ return e(e1,((T2)obj).e1) && e(e2,((T2)obj).e2); } else return false; } @Override public int hashCode(){ return (e1==null?0:e1.hashCode())+(e2==null?0:e2.hashCode()); } @Override public String toString(){ return "("+e1+","+e2+")"; } } public static class T3<E1,E2,E3>{ public final E1 e1; public final E2 e2; public final E3 e3; public T3(final E1 e1,final E2 e2,final E3 e3){ this.e1=e1; this.e2=e2; this.e3=e3; } @Override public boolean equals(Object obj){ if(obj instanceof T3){ return e(e1,((T3)obj).e1) && e(e2,((T3)obj).e2) && e(e3,((T3)obj).e3); } else return false; } @Override public int hashCode(){ return (e1==null?0:e1.hashCode())+(e2==null?0:e2.hashCode())+(e3==null?0:e3.hashCode()); } @Override public String toString(){ return "("+e1+","+e2+","+e3+")"; } } public static class T4<E1,E2,E3,E4>{ public final E1 e1; public final E2 e2; public final E3 e3; public final E4 e4; public T4(final E1 e1,final E2 e2,final E3 e3,final E4 e4){ this.e1=e1; this.e2=e2; this.e3=e3; this.e4=e4; } @Override public boolean equals(Object obj){ if(obj instanceof T4){ return e(e1,((T4)obj).e1) && e(e2,((T4)obj).e2) && e(e3,((T4)obj).e3) && e(e4,((T4)obj).e4); } else return false; } @Override public int hashCode(){ return (e1==null?0:e1.hashCode())+(e2==null?0:e2.hashCode())+(e3==null?0:e3.hashCode())+(e4==null?0:e4.hashCode()); } @Override public String toString(){ return "("+e1+","+e2+","+e3+","+e4+")"; } } public static class T5<E1,E2,E3,E4,E5>{ public final E1 e1; public final E2 e2; public final E3 e3; public final E4 e4; public final E5 e5; public T5(final E1 e1,final E2 e2,final E3 e3,final E4 e4,final E5 e5){ this.e1=e1; this.e2=e2; this.e3=e3; this.e4=e4; this.e5=e5; } @Override public boolean equals(Object obj){ if(obj instanceof T5){ return e(e1,((T5)obj).e1) && e(e2,((T5)obj).e2) && e(e3,((T5)obj).e3) && e(e4,((T5)obj).e4) && e(e5,((T5)obj).e5); } else return false; } @Override public int hashCode(){ return (e1==null?0:e1.hashCode())+(e2==null?0:e2.hashCode())+(e3==null?0:e3.hashCode())+(e4==null?0:e4.hashCode())+(e5==null?0:e5.hashCode()); } @Override public String toString(){ return "("+e1+","+e2+","+e3+","+e4+","+e5+")"; } } public static class T6<E1,E2,E3,E4,E5,E6>{ public final E1 e1; public final E2 e2; public final E3 e3; public final E4 e4; public final E5 e5; public final E6 e6; public T6(final E1 e1,final E2 e2,final E3 e3,final E4 e4,final E5 e5,final E6 e6){ this.e1=e1; this.e2=e2; this.e3=e3; this.e4=e4; this.e5=e5; this.e6=e6; } @Override public boolean equals(Object obj){ if(obj instanceof T6){ return e(e1,((T6)obj).e1) && e(e2,((T6)obj).e2) && e(e3,((T6)obj).e3) && e(e4,((T6)obj).e4) && e(e5,((T6)obj).e5) && e(e6,((T6)obj).e6); } else return false; } @Override public int hashCode(){ return (e1==null?0:e1.hashCode())+(e2==null?0:e2.hashCode())+(e3==null?0:e3.hashCode())+(e4==null?0:e4.hashCode())+(e5==null?0:e5.hashCode())+(e6==null?0:e6.hashCode()); } @Override public String toString(){ return "("+e1+","+e2+","+e3+","+e4+","+e5+","+e6+")"; } } public static <E1,E2> T2<E1,E2> t2(final E1 e1,final E2 e2){ return new T2<E1,E2>(e1,e2); } public static <E1,E2,E3> T3<E1,E2,E3> t3(final E1 e1,final E2 e2,final E3 e3){ return new T3<E1,E2,E3>(e1,e2,e3); } public static <E1,E2,E3,E4> T4<E1,E2,E3,E4> t4(final E1 e1,final E2 e2,final E3 e3,final E4 e4){ return new T4<E1,E2,E3,E4>(e1,e2,e3,e4); } public static <E1,E2,E3,E4,E5> T5<E1,E2,E3,E4,E5> t5(final E1 e1,final E2 e2,final E3 e3,final E4 e4,final E5 e5){ return new T5<E1,E2,E3,E4,E5>(e1,e2,e3,e4,e5); } public static <E1,E2,E3,E4,E5,E6> T6<E1,E2,E3,E4,E5,E6> t6(final E1 e1,final E2 e2,final E3 e3,final E4 e4,final E5 e5,final E6 e6){ return new T6<E1,E2,E3,E4,E5,E6>(e1,e2,e3,e4,e5,e6); } }
7,615
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Functional.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/Functional.java
package org.wandora.utils; public class Functional { public static interface Fn0<R> { public R invoke(); } public static interface Fn1<R, T0> { public R invoke(T0 t0); } public static interface Fn2<R, T0, T1> { public R invoke(T0 t0, T1 t1); } public static interface Fn3<R, T0, T1, T2> { public R invoke(T0 t0, T1 t1, T2 t2); } public static interface Fn4<R, T0, T1, T2, T3> { public R invoke(T0 t0, T1 t1, T2 t2, T3 t3); } public static interface Fn5<R, T0, T1, T2, T3, T4> { public R invoke(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4); } public static interface Pr0 { public void invoke(); } public static interface Pr1<T0> { public void invoke(T0 t0); } public static interface Pr2<T0, T1> { public void invoke(T0 t0, T1 t1); } public static <R, T0> Fn0<R> partial(final Fn1<R, T0> fn, final T0 t0) { return new Fn0<R>() { public R invoke() { return fn.invoke(t0); }}; } /** * partial :: ((a, b) -> c) -> a -> (b -> c) * partial f x = \y -> f (x, y) * @param fn * @param t0 * @return */ public static <R, T0, T1> Fn1<R, T1> partial( final Fn2<R, T0, T1> fn, final T0 t0) { return new Fn1<R, T1>() { public R invoke(T1 t1) { return fn.invoke(t0, t1); } }; } public static <R, T0, T1, T2> Fn2<R, T1, T2> partial( final Fn3<R, T0, T1, T2> fn, final T0 t0) { return new Fn2<R, T1, T2>() { public R invoke(T1 t1, T2 t2) { return fn.invoke(t0, t1, t2); } }; } public static <R, T0, T1, T2, T3> Fn3<R, T1, T2, T3> partial( final Fn4<R, T0, T1, T2, T3> fn, final T0 t0) { return new Fn3<R, T1, T2, T3>() { public R invoke(T1 t1, T2 t2, T3 t3) { return fn.invoke(t0, t1, t2, t3); } }; } /** * curry :: ((a, b) -> c) -> a -> b -> c * curry f x y = f (x, y) * @param fn * @return */ public static <R, T0, T1> Fn1<Fn1<R, T1>, T0> curry(final Fn2<R, T0, T1> fn) { return new Fn1<Fn1<R, T1>, T0>() { public Fn1<R, T1> invoke(final T0 t0) { return new Fn1<R, T1>() { public R invoke(T1 t1) { return fn.invoke(t0, t1); } }; } }; } /** * curry :: ((a, b, c) -> d) -> a -> b -> c -> d * curry f x y z = f (x, y, z) * @param fn * @return */ public static <R, T0, T1, T2> Fn1<Fn1<Fn1<R, T2>, T1>, T0> curry(final Fn3<R, T0, T1, T2> fn) { return new Fn1<Fn1<Fn1<R, T2>, T1>, T0>() { public Fn1<Fn1<R, T2>, T1> invoke(final T0 t0) { return new Fn1<Fn1<R, T2>, T1>() { public Fn1<R, T2> invoke(final T1 t1) { return new Fn1<R, T2>() { public R invoke(final T2 t2) { return fn.invoke(t0, t1, t2); } }; } }; } }; } public static <R, T0, T1, T2, T3> Fn1<Fn1<Fn1<Fn1<R, T3>, T2>, T1>, T0> curry(final Fn4<R, T0, T1, T2, T3> fn) { return new Fn1<Fn1<Fn1<Fn1<R, T3>, T2>, T1>, T0>() { public Fn1<Fn1<Fn1<R, T3>, T2>, T1> invoke(final T0 t0) { return new Fn1<Fn1<Fn1<R, T3>, T2>, T1>() { public Fn1<Fn1<R, T3>, T2> invoke(final T1 t1) { return new Fn1<Fn1<R, T3>, T2>() { public Fn1<R, T3> invoke(final T2 t2) { return new Fn1<R, T3>() { public R invoke(final T3 t3) { return fn.invoke(t0, t1, t2, t3); } }; } }; } }; } }; } /** * flip :: ((a, b) -> c) -> (b, a) -> c * flip f (y, x) = f (x, y) * @param fn * @return */ public static <R, T0, T1> Fn2<R, T1, T0> flip(final Fn2<R, T0, T1> fn) { return new Fn2<R, T1, T0>() { public R invoke(T1 t1, T0 t0) { return fn.invoke(t0, t1); } }; } /** * flip :: (a -> b -> c) -> b -> a -> c * flip f y x = f x y * @param fn * @return */ public static <R, T0, T1> Fn1<Fn1<R, T0>, T1> flip(final Fn1<Fn1<R, T1>, T0> fn) { return new Fn1<Fn1<R, T0>, T1>() { public Fn1<R, T0> invoke(final T1 t1) { return new Fn1<R, T0>() { public R invoke(T0 t0) { return fn.invoke(t0).invoke(t1); } }; } }; } }
4,630
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EasyHash.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/EasyHash.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * EasyHash.java * * Created on April 26, 2001, 11:57 AM */ package org.wandora.utils; import java.util.HashMap; /** * EasyHash is an extended HashMap with one added constructor and one * initialization method. * * The new constructor makes it possible to more easily create a new HashMap * instance. For example, this associates letters with numbers: * <code>EasyHash eh=new EasyHash(new Object[] { * "a",Integer.valueOf(1), * "b",Integer.valueOf(2), * "c",Integer.valueOf(3), * "d",Integer.valueOf(4) * });</code> * * @author Olli Lyytinen * @see java.util.HashMap */ /* * EasyHash is an extended HashMap with one added costructor and one * initialization method. * * The new constructor makes it possible to more easily create a new HashMap * instance. For example, this associates letters with numbers: * EasyHash eh=new EasyHash(new Object[] { * "a",Integer.valueOf(1), * "b",Integer.valueOf(2), * "c",Integer.valueOf(3), * "d",Integer.valueOf(4) * }); * * The setArray can be used to add values to this EasyHash in a similar way. * In both the constructor and setArray, the given array must contain an even * number of Object. If it doesen't, the last Object will be ignored. */ public class EasyHash<K,V> extends HashMap<K,V> { /** * Creates new EasyHash from an array of objects. * * @param a The objects to be fed to <code>setArray</code>. * <code>a[n]</code> will be associated with <code>a[n+1]</code>. * The number of elements in <code>a</code> should therefore be * even. If it isn't, the last element will be ignored. */ public EasyHash(Object ... a) { setArray(a); } /** * Adds the given objects to this EasyHash. * * @param a The objects to be added. * <code>a[n]</code> will be associated with <code>a[n+1]</code>. * The number of elements in <code>a</code> should therefore be * even. If it isn't, the last element will be ignored. */ public void setArray(Object ... a){ for(int i=0;i+1<a.length;i+=2){ this.put((K)a[i],(V)a[i+1]); } } }
3,086
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ReaderWriterLock.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ReaderWriterLock.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ReaderWriterLock.java * * Created on July 9, 2004, 2:17 PM */ package org.wandora.utils; /** * * ReaderWriterLock is a locking mechanism that allows several readers to access a resource simultaneously * but only single writer. When writer has locked the resource neither readers nor other writers are allowed * acces until the resource has been released by the writer who has the lock. Also writer will not get a lock * if a reader or some other writer has the lock. This lock operates with the writers-first principle meaning * that if a writer is waiting for the lock, no more readers are allowed to get the lock. When you get a lock * (and the get*Lock method returns true) you should always put the following code inside a try block and release * the lock in the finally block after the try. This will ensure that the lock is released, even if an exception is * thrown and not handled. If you fail to release the lock, your application will most likely get stuck. * * Note that if the same thread tries to get a second writer lock, the thread will get blocked indefinitely and * also block any other threads trying to use this lock. This behavior is somewhat different than synchronized * blocks in java which will get a lock for the executing thread to the specified object's monitor if, it does * not have that allready. * * Take care that you release exactly as many locks as you acquire. If you release more, a RuntimeException * will be thrown and if you release less, others won't be able to get the lock. * * @author olli */ public class ReaderWriterLock { public static final int LOCK_READ=0; public static final int LOCK_WRITE=1; private int numReaders; private int numWriters; private int waitingWriters; public ReaderWriterLock(){ numReaders=0; numWriters=0; waitingWriters=0; } public synchronized boolean getReaderLockNonBlocking(){ if(numWriters==0 && waitingWriters==0) { numReaders++; return true; } else return false; } public synchronized boolean getReaderLock(){ while(numWriters>0 || waitingWriters>0) { try{ this.wait(); }catch(InterruptedException ie){return false;} } numReaders++; return true; } public synchronized void releaseReaderLock(){ numReaders--; if(numReaders<0) throw new RuntimeException("Too many readers realeased"); this.notifyAll(); } public synchronized boolean getWriterLockNonBlocking(){ if(numWriters==0 && numReaders==0) { numWriters++; return true; } else return false; } public synchronized boolean getWriterLock(){ waitingWriters++; while(numWriters>0 || numReaders>0) { try{ this.wait(); }catch(InterruptedException ie){return false;} } waitingWriters--; numWriters++; return true; } public synchronized void releaseWriterLock(){ numWriters--; if(numWriters<0) throw new RuntimeException("Too many writers realeased"); this.notifyAll(); } public synchronized boolean getLockNonBlocking(int type){ if(type==LOCK_READ) return getReaderLockNonBlocking(); else return getWriterLockNonBlocking(); } public synchronized boolean getLock(int type){ if(type==LOCK_READ) return getReaderLock(); else return getWriterLock(); } public synchronized void releaseLock(int type){ if(type==LOCK_READ) releaseReaderLock(); else releaseWriterLock(); } }
4,544
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HTMLEntitiesCoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/HTMLEntitiesCoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * HTMLEntitiesCoder.java * * Created on 3. joulukuuta 2004, 10:36 */ package org.wandora.utils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * This class has mappings from html entities to characters and vica versa * as specified in http://www.w3.org/TR/REC-html40/sgml/entities.html . There * are also methods to encode and decode html entities in a text. * @author olli */ public class HTMLEntitiesCoder { /** * Maps html entities to characters. The keyes are html entities * without the ampersand and semicolon. Values are Character objects. * For example there is a mapping from the String "nbsp" to Character with * char code 160. */ public static final Map entitiesTable = new EasyHash(new Object[]{ "nbsp",Character.valueOf((char)160), /* no-break space = non-breaking space, U+00A0 ISOnum */ "iexcl",Character.valueOf((char)161), /* inverted exclamation mark, U+00A1 ISOnum */ "cent",Character.valueOf((char)162), /* cent sign, U+00A2 ISOnum */ "pound",Character.valueOf((char)163), /* pound sign, U+00A3 ISOnum */ "curren",Character.valueOf((char)164), /* currency sign, U+00A4 ISOnum */ "yen",Character.valueOf((char)165), /* yen sign = yuan sign, U+00A5 ISOnum */ "brvbar",Character.valueOf((char)166), /* broken bar = broken vertical bar, U+00A6 ISOnum */ "sect",Character.valueOf((char)167), /* section sign, U+00A7 ISOnum */ "uml",Character.valueOf((char)168), /* diaeresis = spacing diaeresis, U+00A8 ISOdia */ "copy",Character.valueOf((char)169), /* copyright sign, U+00A9 ISOnum */ "ordf",Character.valueOf((char)170), /* feminine ordinal indicator, U+00AA ISOnum */ "laquo",Character.valueOf((char)171), /* left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum */ "not",Character.valueOf((char)172), /* not sign, U+00AC ISOnum */ "shy",Character.valueOf((char)173), /* soft hyphen = discretionary hyphen, U+00AD ISOnum */ "reg",Character.valueOf((char)174), /* registered sign = registered trade mark sign, U+00AE ISOnum */ "macr",Character.valueOf((char)175), /* macron = spacing macron = overline = APL overbar, U+00AF ISOdia */ "deg",Character.valueOf((char)176), /* degree sign, U+00B0 ISOnum */ "plusmn",Character.valueOf((char)177), /* plus-minus sign = plus-or-minus sign, U+00B1 ISOnum */ "sup2",Character.valueOf((char)178), /* superscript two = superscript digit two = squared, U+00B2 ISOnum */ "sup3",Character.valueOf((char)179), /* superscript three = superscript digit three = cubed, U+00B3 ISOnum */ "acute",Character.valueOf((char)180), /* acute accent = spacing acute, U+00B4 ISOdia */ "micro",Character.valueOf((char)181), /* micro sign, U+00B5 ISOnum */ "para",Character.valueOf((char)182), /* pilcrow sign = paragraph sign, U+00B6 ISOnum */ "middot",Character.valueOf((char)183), /* middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum */ "cedil",Character.valueOf((char)184), /* cedilla = spacing cedilla, U+00B8 ISOdia */ "sup1",Character.valueOf((char)185), /* superscript one = superscript digit one, U+00B9 ISOnum */ "ordm",Character.valueOf((char)186), /* masculine ordinal indicator, U+00BA ISOnum */ "raquo",Character.valueOf((char)187), /* right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum */ "frac14",Character.valueOf((char)188), /* vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum */ "frac12",Character.valueOf((char)189), /* vulgar fraction one half = fraction one half, U+00BD ISOnum */ "frac34",Character.valueOf((char)190), /* vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum */ "iquest",Character.valueOf((char)191), /* inverted question mark = turned question mark, U+00BF ISOnum */ "Agrave",Character.valueOf((char)192), /* latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 */ "Aacute",Character.valueOf((char)193), /* latin capital letter A with acute, U+00C1 ISOlat1 */ "Acirc",Character.valueOf((char)194), /* latin capital letter A with circumflex, U+00C2 ISOlat1 */ "Atilde",Character.valueOf((char)195), /* latin capital letter A with tilde, U+00C3 ISOlat1 */ "Auml",Character.valueOf((char)196), /* latin capital letter A with diaeresis, U+00C4 ISOlat1 */ "Aring",Character.valueOf((char)197), /* latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 */ "AElig",Character.valueOf((char)198), /* latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 */ "Ccedil",Character.valueOf((char)199), /* latin capital letter C with cedilla, U+00C7 ISOlat1 */ "Egrave",Character.valueOf((char)200), /* latin capital letter E with grave, U+00C8 ISOlat1 */ "Eacute",Character.valueOf((char)201), /* latin capital letter E with acute, U+00C9 ISOlat1 */ "Ecirc",Character.valueOf((char)202), /* latin capital letter E with circumflex, U+00CA ISOlat1 */ "Euml",Character.valueOf((char)203), /* latin capital letter E with diaeresis, U+00CB ISOlat1 */ "Igrave",Character.valueOf((char)204), /* latin capital letter I with grave, U+00CC ISOlat1 */ "Iacute",Character.valueOf((char)205), /* latin capital letter I with acute, U+00CD ISOlat1 */ "Icirc",Character.valueOf((char)206), /* latin capital letter I with circumflex, U+00CE ISOlat1 */ "Iuml",Character.valueOf((char)207), /* latin capital letter I with diaeresis, U+00CF ISOlat1 */ "ETH",Character.valueOf((char)208), /* latin capital letter ETH, U+00D0 ISOlat1 */ "Ntilde",Character.valueOf((char)209), /* latin capital letter N with tilde, U+00D1 ISOlat1 */ "Ograve",Character.valueOf((char)210), /* latin capital letter O with grave, U+00D2 ISOlat1 */ "Oacute",Character.valueOf((char)211), /* latin capital letter O with acute, U+00D3 ISOlat1 */ "Ocirc",Character.valueOf((char)212), /* latin capital letter O with circumflex, U+00D4 ISOlat1 */ "Otilde",Character.valueOf((char)213), /* latin capital letter O with tilde, U+00D5 ISOlat1 */ "Ouml",Character.valueOf((char)214), /* latin capital letter O with diaeresis, U+00D6 ISOlat1 */ "times",Character.valueOf((char)215), /* multiplication sign, U+00D7 ISOnum */ "Oslash",Character.valueOf((char)216), /* latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 */ "Ugrave",Character.valueOf((char)217), /* latin capital letter U with grave, U+00D9 ISOlat1 */ "Uacute",Character.valueOf((char)218), /* latin capital letter U with acute, U+00DA ISOlat1 */ "Ucirc",Character.valueOf((char)219), /* latin capital letter U with circumflex, U+00DB ISOlat1 */ "Uuml",Character.valueOf((char)220), /* latin capital letter U with diaeresis, U+00DC ISOlat1 */ "Yacute",Character.valueOf((char)221), /* latin capital letter Y with acute, U+00DD ISOlat1 */ "THORN",Character.valueOf((char)222), /* latin capital letter THORN, U+00DE ISOlat1 */ "szlig",Character.valueOf((char)223), /* latin small letter sharp s = ess-zed, U+00DF ISOlat1 */ "agrave",Character.valueOf((char)224), /* latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 */ "aacute",Character.valueOf((char)225), /* latin small letter a with acute, U+00E1 ISOlat1 */ "acirc",Character.valueOf((char)226), /* latin small letter a with circumflex, U+00E2 ISOlat1 */ "atilde",Character.valueOf((char)227), /* latin small letter a with tilde, U+00E3 ISOlat1 */ "auml",Character.valueOf((char)228), /* latin small letter a with diaeresis, U+00E4 ISOlat1 */ "aring",Character.valueOf((char)229), /* latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 */ "aelig",Character.valueOf((char)230), /* latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 */ "ccedil",Character.valueOf((char)231), /* latin small letter c with cedilla, U+00E7 ISOlat1 */ "egrave",Character.valueOf((char)232), /* latin small letter e with grave, U+00E8 ISOlat1 */ "eacute",Character.valueOf((char)233), /* latin small letter e with acute, U+00E9 ISOlat1 */ "ecirc",Character.valueOf((char)234), /* latin small letter e with circumflex, U+00EA ISOlat1 */ "euml",Character.valueOf((char)235), /* latin small letter e with diaeresis, U+00EB ISOlat1 */ "igrave",Character.valueOf((char)236), /* latin small letter i with grave, U+00EC ISOlat1 */ "iacute",Character.valueOf((char)237), /* latin small letter i with acute, U+00ED ISOlat1 */ "icirc",Character.valueOf((char)238), /* latin small letter i with circumflex, U+00EE ISOlat1 */ "iuml",Character.valueOf((char)239), /* latin small letter i with diaeresis, U+00EF ISOlat1 */ "eth",Character.valueOf((char)240), /* latin small letter eth, U+00F0 ISOlat1 */ "ntilde",Character.valueOf((char)241), /* latin small letter n with tilde, U+00F1 ISOlat1 */ "ograve",Character.valueOf((char)242), /* latin small letter o with grave, U+00F2 ISOlat1 */ "oacute",Character.valueOf((char)243), /* latin small letter o with acute, U+00F3 ISOlat1 */ "ocirc",Character.valueOf((char)244), /* latin small letter o with circumflex, U+00F4 ISOlat1 */ "otilde",Character.valueOf((char)245), /* latin small letter o with tilde, U+00F5 ISOlat1 */ "ouml",Character.valueOf((char)246), /* latin small letter o with diaeresis, U+00F6 ISOlat1 */ "divide",Character.valueOf((char)247), /* division sign, U+00F7 ISOnum */ "oslash",Character.valueOf((char)248), /* latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 */ "ugrave",Character.valueOf((char)249), /* latin small letter u with grave, U+00F9 ISOlat1 */ "uacute",Character.valueOf((char)250), /* latin small letter u with acute, U+00FA ISOlat1 */ "ucirc",Character.valueOf((char)251), /* latin small letter u with circumflex, U+00FB ISOlat1 */ "uuml",Character.valueOf((char)252), /* latin small letter u with diaeresis, U+00FC ISOlat1 */ "yacute",Character.valueOf((char)253), /* latin small letter y with acute, U+00FD ISOlat1 */ "thorn",Character.valueOf((char)254), /* latin small letter thorn, U+00FE ISOlat1 */ "yuml",Character.valueOf((char)255), /* latin small letter y with diaeresis, U+00FF ISOlat1 */ /* Latin Extended-B */ "fnof",Character.valueOf((char)402), /* latin small f with hook = function = florin, U+0192 ISOtech */ /* Greek */ "Alpha",Character.valueOf((char)913), /* greek capital letter alpha, U+0391 */ "Beta",Character.valueOf((char)914), /* greek capital letter beta, U+0392 */ "Gamma",Character.valueOf((char)915), /* greek capital letter gamma, U+0393 ISOgrk3 */ "Delta",Character.valueOf((char)916), /* greek capital letter delta, U+0394 ISOgrk3 */ "Epsilon",Character.valueOf((char)917), /* greek capital letter epsilon, U+0395 */ "Zeta",Character.valueOf((char)918), /* greek capital letter zeta, U+0396 */ "Eta",Character.valueOf((char)919), /* greek capital letter eta, U+0397 */ "Theta",Character.valueOf((char)920), /* greek capital letter theta, U+0398 ISOgrk3 */ "Iota",Character.valueOf((char)921), /* greek capital letter iota, U+0399 */ "Kappa",Character.valueOf((char)922), /* greek capital letter kappa, U+039A */ "Lambda",Character.valueOf((char)923), /* greek capital letter lambda, U+039B ISOgrk3 */ "Mu",Character.valueOf((char)924), /* greek capital letter mu, U+039C */ "Nu",Character.valueOf((char)925), /* greek capital letter nu, U+039D */ "Xi",Character.valueOf((char)926), /* greek capital letter xi, U+039E ISOgrk3 */ "Omicron",Character.valueOf((char)927), /* greek capital letter omicron, U+039F */ "Pi",Character.valueOf((char)928), /* greek capital letter pi, U+03A0 ISOgrk3 */ "Rho",Character.valueOf((char)929), /* greek capital letter rho, U+03A1 */ /* there is no Sigmaf, and no U+03A2 character either */ "Sigma",Character.valueOf((char)931), /* greek capital letter sigma, U+03A3 ISOgrk3 */ "Tau",Character.valueOf((char)932), /* greek capital letter tau, U+03A4 */ "Upsilon",Character.valueOf((char)933), /* greek capital letter upsilon, U+03A5 ISOgrk3 */ "Phi",Character.valueOf((char)934), /* greek capital letter phi, U+03A6 ISOgrk3 */ "Chi",Character.valueOf((char)935), /* greek capital letter chi, U+03A7 */ "Psi",Character.valueOf((char)936), /* greek capital letter psi, U+03A8 ISOgrk3 */ "Omega",Character.valueOf((char)937), /* greek capital letter omega, U+03A9 ISOgrk3 */ "alpha",Character.valueOf((char)945), /* greek small letter alpha, U+03B1 ISOgrk3 */ "beta",Character.valueOf((char)946), /* greek small letter beta, U+03B2 ISOgrk3 */ "gamma",Character.valueOf((char)947), /* greek small letter gamma, U+03B3 ISOgrk3 */ "delta",Character.valueOf((char)948), /* greek small letter delta, U+03B4 ISOgrk3 */ "epsilon",Character.valueOf((char)949), /* greek small letter epsilon, U+03B5 ISOgrk3 */ "zeta",Character.valueOf((char)950), /* greek small letter zeta, U+03B6 ISOgrk3 */ "eta",Character.valueOf((char)951), /* greek small letter eta, U+03B7 ISOgrk3 */ "theta",Character.valueOf((char)952), /* greek small letter theta, U+03B8 ISOgrk3 */ "iota",Character.valueOf((char)953), /* greek small letter iota, U+03B9 ISOgrk3 */ "kappa",Character.valueOf((char)954), /* greek small letter kappa, U+03BA ISOgrk3 */ "lambda",Character.valueOf((char)955), /* greek small letter lambda, U+03BB ISOgrk3 */ "mu",Character.valueOf((char)956), /* greek small letter mu, U+03BC ISOgrk3 */ "nu",Character.valueOf((char)957), /* greek small letter nu, U+03BD ISOgrk3 */ "xi",Character.valueOf((char)958), /* greek small letter xi, U+03BE ISOgrk3 */ "omicron",Character.valueOf((char)959), /* greek small letter omicron, U+03BF NEW */ "pi",Character.valueOf((char)960), /* greek small letter pi, U+03C0 ISOgrk3 */ "rho",Character.valueOf((char)961), /* greek small letter rho, U+03C1 ISOgrk3 */ "sigmaf",Character.valueOf((char)962), /* greek small letter final sigma, U+03C2 ISOgrk3 */ "sigma",Character.valueOf((char)963), /* greek small letter sigma, U+03C3 ISOgrk3 */ "tau",Character.valueOf((char)964), /* greek small letter tau, U+03C4 ISOgrk3 */ "upsilon",Character.valueOf((char)965), /* greek small letter upsilon, U+03C5 ISOgrk3 */ "phi",Character.valueOf((char)966), /* greek small letter phi, U+03C6 ISOgrk3 */ "chi",Character.valueOf((char)967), /* greek small letter chi, U+03C7 ISOgrk3 */ "psi",Character.valueOf((char)968), /* greek small letter psi, U+03C8 ISOgrk3 */ "omega",Character.valueOf((char)969), /* greek small letter omega, U+03C9 ISOgrk3 */ "thetasym",Character.valueOf((char)977), /* greek small letter theta symbol, U+03D1 NEW */ "upsih",Character.valueOf((char)978), /* greek upsilon with hook symbol, U+03D2 NEW */ "piv",Character.valueOf((char)982), /* greek pi symbol, U+03D6 ISOgrk3 */ /* General Punctuation */ "bull",Character.valueOf((char)8226), /* bullet = black small circle, U+2022 ISOpub */ /* bullet is NOT the same as bullet operator, U+2219 */ "hellip",Character.valueOf((char)8230), /* horizontal ellipsis = three dot leader, U+2026 ISOpub */ "prime",Character.valueOf((char)8242), /* prime = minutes = feet, U+2032 ISOtech */ "Prime",Character.valueOf((char)8243), /* double prime = seconds = inches, U+2033 ISOtech */ "oline",Character.valueOf((char)8254), /* overline = spacing overscore, U+203E NEW */ "frasl",Character.valueOf((char)8260), /* fraction slash, U+2044 NEW */ /* Letterlike Symbols */ "weierp",Character.valueOf((char)8472), /* script capital P = power set = Weierstrass p, U+2118 ISOamso */ "image",Character.valueOf((char)8465), /* blackletter capital I = imaginary part, U+2111 ISOamso */ "real",Character.valueOf((char)8476), /* blackletter capital R = real part symbol, U+211C ISOamso */ "trade",Character.valueOf((char)8482), /* trade mark sign, U+2122 ISOnum */ "alefsym",Character.valueOf((char)8501), /* alef symbol = first transfinite cardinal, U+2135 NEW */ /* alef symbol is NOT the same as hebrew letter alef, U+05D0 although the same glyph could be used to depict both characters */ /* Arrows */ "larr",Character.valueOf((char)8592), /* leftwards arrow, U+2190 ISOnum */ "uarr",Character.valueOf((char)8593), /* upwards arrow, U+2191 ISOnum*/ "rarr",Character.valueOf((char)8594), /* rightwards arrow, U+2192 ISOnum */ "darr",Character.valueOf((char)8595), /* downwards arrow, U+2193 ISOnum */ "harr",Character.valueOf((char)8596), /* left right arrow, U+2194 ISOamsa */ "crarr",Character.valueOf((char)8629), /* downwards arrow with corner leftwards = carriage return, U+21B5 NEW */ "lArr",Character.valueOf((char)8656), /* leftwards double arrow, U+21D0 ISOtech */ /* ISO 10646 does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */ "uArr",Character.valueOf((char)8657), /* upwards double arrow, U+21D1 ISOamsa */ "rArr",Character.valueOf((char)8658), /* rightwards double arrow, U+21D2 ISOtech */ /* ISO 10646 does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */ "dArr",Character.valueOf((char)8659), /* downwards double arrow, U+21D3 ISOamsa */ "hArr",Character.valueOf((char)8660), /* left right double arrow, U+21D4 ISOamsa */ /* Mathematical Operators */ "forall",Character.valueOf((char)8704), /* for all, U+2200 ISOtech */ "part",Character.valueOf((char)8706), /* partial differential, U+2202 ISOtech */ "exist",Character.valueOf((char)8707), /* there exists, U+2203 ISOtech */ "empty",Character.valueOf((char)8709), /* empty set = null set = diameter, U+2205 ISOamso */ "nabla",Character.valueOf((char)8711), /* nabla = backward difference, U+2207 ISOtech */ "isin",Character.valueOf((char)8712), /* element of, U+2208 ISOtech */ "notin",Character.valueOf((char)8713), /* not an element of, U+2209 ISOtech */ "ni",Character.valueOf((char)8715), /* contains as member, U+220B ISOtech */ /* should there be a more memorable name than 'ni'? */ "prod",Character.valueOf((char)8719), /* n-ary product = product sign, U+220F ISOamsb */ /* prod is NOT the same character as U+03A0 'greek capital letter pi' though the same glyph might be used for both */ "sum",Character.valueOf((char)8721), /* n-ary sumation, U+2211 ISOamsb */ /* sum is NOT the same character as U+03A3 'greek capital letter sigma' though the same glyph might be used for both */ "minus",Character.valueOf((char)8722), /* minus sign, U+2212 ISOtech */ "lowast",Character.valueOf((char)8727), /* asterisk operator, U+2217 ISOtech */ "radic",Character.valueOf((char)8730), /* square root = radical sign, U+221A ISOtech */ "prop",Character.valueOf((char)8733), /* proportional to, U+221D ISOtech */ "infin",Character.valueOf((char)8734), /* infinity, U+221E ISOtech */ "ang",Character.valueOf((char)8736), /* angle, U+2220 ISOamso */ "and",Character.valueOf((char)8743), /* logical and = wedge, U+2227 ISOtech */ "or",Character.valueOf((char)8744), /* logical or = vee, U+2228 ISOtech */ "cap",Character.valueOf((char)8745), /* intersection = cap, U+2229 ISOtech */ "cup",Character.valueOf((char)8746), /* union = cup, U+222A ISOtech */ "int",Character.valueOf((char)8747), /* integral, U+222B ISOtech */ "there4",Character.valueOf((char)8756), /* therefore, U+2234 ISOtech */ "sim",Character.valueOf((char)8764), /* tilde operator = varies with = similar to, U+223C ISOtech */ /* tilde operator is NOT the same character as the tilde, U+007E, although the same glyph might be used to represent both */ "cong",Character.valueOf((char)8773), /* approximately equal to, U+2245 ISOtech */ "asymp",Character.valueOf((char)8776), /* almost equal to = asymptotic to, U+2248 ISOamsr */ "ne",Character.valueOf((char)8800), /* not equal to, U+2260 ISOtech */ "equiv",Character.valueOf((char)8801), /* identical to, U+2261 ISOtech */ "le",Character.valueOf((char)8804), /* less-than or equal to, U+2264 ISOtech */ "ge",Character.valueOf((char)8805), /* greater-than or equal to, U+2265 ISOtech */ "sub",Character.valueOf((char)8834), /* subset of, U+2282 ISOtech */ "sup",Character.valueOf((char)8835), /* superset of, U+2283 ISOtech */ /* note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font encoding and is not included. Should it be, for symmetry? It is in ISOamsn */ "nsub",Character.valueOf((char)8836), /* not a subset of, U+2284 ISOamsn */ "sube",Character.valueOf((char)8838), /* subset of or equal to, U+2286 ISOtech */ "supe",Character.valueOf((char)8839), /* superset of or equal to, U+2287 ISOtech */ "oplus",Character.valueOf((char)8853), /* circled plus = direct sum, U+2295 ISOamsb */ "otimes",Character.valueOf((char)8855), /* circled times = vector product, U+2297 ISOamsb */ "perp",Character.valueOf((char)8869), /* up tack = orthogonal to = perpendicular, U+22A5 ISOtech */ "sdot",Character.valueOf((char)8901), /* dot operator, U+22C5 ISOamsb */ /* dot operator is NOT the same character as U+00B7 middle dot */ /* Miscellaneous Technical */ "lceil",Character.valueOf((char)8968), /* left ceiling = apl upstile, U+2308 ISOamsc */ "rceil",Character.valueOf((char)8969), /* right ceiling, U+2309 ISOamsc */ "lfloor",Character.valueOf((char)8970), /* left floor = apl downstile, U+230A ISOamsc */ "rfloor",Character.valueOf((char)8971), /* right floor, U+230B ISOamsc */ "lang",Character.valueOf((char)9001), /* left-pointing angle bracket = bra, U+2329 ISOtech */ /* lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation mark' */ "rang",Character.valueOf((char)9002), /* right-pointing angle bracket = ket, U+232A ISOtech */ /* rang is NOT the same character as U+003E 'greater than' or U+203A 'single right-pointing angle quotation mark' */ /* Geometric Shapes */ "loz",Character.valueOf((char)9674), /* lozenge, U+25CA ISOpub */ /* Miscellaneous Symbols */ "spades",Character.valueOf((char)9824), /* black spade suit, U+2660 ISOpub */ /* black here seems to mean filled as opposed to hollow */ "clubs",Character.valueOf((char)9827), /* black club suit = shamrock, U+2663 ISOpub */ "hearts",Character.valueOf((char)9829), /* black heart suit = valentine, U+2665 ISOpub */ "diams",Character.valueOf((char)9830), /* black diamond suit, U+2666 ISOpub */ /* C0 Controls and Basic Latin */ "quot",Character.valueOf((char)34) , /* quotation mark = APL quote, U+0022 ISOnum */ "amp",Character.valueOf((char)38) , /* ampersand, U+0026 ISOnum */ "lt",Character.valueOf((char)60) , /* less-than sign, U+003C ISOnum */ "gt",Character.valueOf((char)62) , /* greater-than sign, U+003E ISOnum */ /* Latin Extended-A */ "OElig",Character.valueOf((char)338) , /* latin capital ligature OE, U+0152 ISOlat2 */ "oelig",Character.valueOf((char)339) , /* latin small ligature oe, U+0153 ISOlat2 */ /* ligature is a misnomer, this is a separate character in some languages */ "Scaron",Character.valueOf((char)352) , /* latin capital letter S with caron, U+0160 ISOlat2 */ "scaron",Character.valueOf((char)353) , /* latin small letter s with caron, U+0161 ISOlat2 */ "Yuml",Character.valueOf((char)376) , /* latin capital letter Y with diaeresis, U+0178 ISOlat2 */ /* Spacing Modifier Letters */ "circ",Character.valueOf((char)710) , /* modifier letter circumflex accent, U+02C6 ISOpub */ "tilde",Character.valueOf((char)732) , /* small tilde, U+02DC ISOdia */ /* General Punctuation */ "ensp",Character.valueOf((char)8194), /* en space, U+2002 ISOpub */ "emsp",Character.valueOf((char)8195), /* em space, U+2003 ISOpub */ "thinsp",Character.valueOf((char)8201), /* thin space, U+2009 ISOpub */ "zwnj",Character.valueOf((char)8204), /* zero width non-joiner, U+200C NEW RFC 2070 */ "zwj",Character.valueOf((char)8205), /* zero width joiner, U+200D NEW RFC 2070 */ "lrm",Character.valueOf((char)8206), /* left-to-right mark, U+200E NEW RFC 2070 */ "rlm",Character.valueOf((char)8207), /* right-to-left mark, U+200F NEW RFC 2070 */ "ndash",Character.valueOf((char)8211), /* en dash, U+2013 ISOpub */ "mdash",Character.valueOf((char)8212), /* em dash, U+2014 ISOpub */ "lsquo",Character.valueOf((char)8216), /* left single quotation mark, U+2018 ISOnum */ "rsquo",Character.valueOf((char)8217), /* right single quotation mark, U+2019 ISOnum */ "sbquo",Character.valueOf((char)8218), /* single low-9 quotation mark, U+201A NEW */ "ldquo",Character.valueOf((char)8220), /* left double quotation mark, U+201C ISOnum */ "rdquo",Character.valueOf((char)8221), /* right double quotation mark, U+201D ISOnum */ "bdquo",Character.valueOf((char)8222), /* double low-9 quotation mark, U+201E NEW */ "dagger",Character.valueOf((char)8224), /* dagger, U+2020 ISOpub */ "Dagger",Character.valueOf((char)8225), /* double dagger, U+2021 ISOpub */ "permil",Character.valueOf((char)8240), /* per mille sign, U+2030 ISOtech */ "lsaquo",Character.valueOf((char)8249), /* single left-pointing angle quotation mark, U+2039 ISO proposed */ /* lsaquo is proposed but not yet ISO standardized */ "rsaquo",Character.valueOf((char)8250), /* single right-pointing angle quotation mark, U+203A ISO proposed */ /* rsaquo is proposed but not yet ISO standardized */ "euro",Character.valueOf((char)8364) , /* euro sign, U+20AC NEW */ }); /** * The inverse of table entitiesTable. */ public static final Map inverseTable=new HashMap(); static{ Iterator iter=entitiesTable.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); inverseTable.put(e.getValue(),e.getKey()); } } public static String encode(String text){ return encode(text,true); } /** * Encodes all characters in the text with character code outside range * 32 to 127 (inclusive) and the ampersand and less-than characters. * If trytable is true, tries to find a html entity from the entities table. * If it is false or no suitable entity is found, uses an entity of the * form "&#xxx;" where xxx is the character code. */ public static String encode(String text,boolean trytable){ StringBuffer buf=new StringBuffer(text); int ptr=0; while(ptr<buf.length()){ char c=buf.charAt(ptr); if(c<32 || c>127 || c=='&' || c=='<'){ String ent=null; if(trytable) { ent=(String)inverseTable.get(Character.valueOf(c)); if(ent!=null) ent="&"+ent+";"; } if(ent==null){ ent="&#"+((int)c)+";"; } buf.replace(ptr, ptr+1,ent); ptr+=ent.length(); } else ptr++; } return buf.toString(); } private static int getNumber(String ent){ int ptr=0; char c=ent.charAt(0); boolean hex=false; if(c=='x' || c=='X'){ hex=true; ptr=1; } for(int i=ptr;i<ent.length();i++){ if(!Character.isDigit(ent.charAt(i))) return -1; } return Integer.parseInt(ent,(hex?16:10)); } /** * Decodes html entities in the text. */ public static String decode(String htmlText){ StringBuffer buf=new StringBuffer(htmlText); int ind=-1; int ptr=0; while( (ind=buf.indexOf("&",ptr))!= -1 ){ ptr=ind+1; int ind2=buf.indexOf(";",ind); if(ind2==-1){ continue; } String ent=buf.substring(ind+1,ind2); if(ent.startsWith("#")) { ent = ent.substring(1); } Character cha=(Character)entitiesTable.get(ent); if(cha!=null){ buf.replace(ind, ind2+1,cha.toString()); } else{ int num=getNumber(ent); if(num!=-1){ buf.replace(ind,ind2+1,Character.valueOf((char)num).toString()); } } } return buf.toString(); } /** Creates a new instance of HTMLEntitiesCoder */ public HTMLEntitiesCoder() { } }
39,132
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HttpAuthorizer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/HttpAuthorizer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * HttpAuthorizer.java * * Created on 17. toukokuuta 2006, 12:46 * */ package org.wandora.utils; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import org.wandora.application.Wandora; /** * * @author akivela */ public class HttpAuthorizer extends Options { /** * Creates a new instance of HttpAuthorizer */ public HttpAuthorizer() { } public HttpAuthorizer(String storeResource) { super(storeResource); } public void addAuthorization(URL url, String user, String password) { addAuthorization(makeKeyAddress(url), user, password); } public void addAuthorization(String address, String user, String password) { put(makeKeyAddress(address) + ".user", user); put(makeKeyAddress(address) + ".password", password); } public String getAuthorizedUserFor(URL url) { return getAuthorizedUserFor(makeKeyAddress(url)); } public String getAuthorizedPasswordFor(URL url) { return getAuthorizedPasswordFor(makeKeyAddress(url)); } public String getAuthorizedUserFor(String address) { return get(makeKeyAddress(address) + ".user"); } public String getAuthorizedPasswordFor(String address) { return get(makeKeyAddress(address) + ".password"); } public String quessAuthorizedUserFor(String address) { return get( makeKeyAddress(address) + ".user"); } public String quessAuthorizedPasswordFor(String address) { return get( makeKeyAddress(address) + ".password"); } public String quessAuthorizedUserFor(URL url) { return quessAuthorizedUserFor(makeKeyAddress(url)); } public String quessAuthorizedPasswordFor(URL url) { return quessAuthorizedPasswordFor(makeKeyAddress(url)); } public String makeKeyAddress(String address) { return "httpAuth." + address; } public String makeKeyAddress(URL url) { return url.getHost(); } // ------------------------------------------------------------------------- public URLConnection getAuthorizedAccess(URL url) throws Exception { URLConnection uc = url.openConnection(); Wandora.initUrlConnection(uc); if(uc instanceof HttpURLConnection) { int res = 0; try { res = ((HttpURLConnection) uc).getResponseCode(); } catch(Exception e) { if(e.toString().indexOf("HTTP response code: 401") != -1) { res = HttpURLConnection.HTTP_UNAUTHORIZED; } } boolean tried = false; if(res == HttpURLConnection.HTTP_UNAUTHORIZED) { String authUser = quessAuthorizedUserFor(url); String authPassword = quessAuthorizedPasswordFor(url); if(authUser != null && authPassword != null) { String userPassword = authUser + ":" + authPassword; // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); String encoding = Base64.encodeBytes(userPassword.getBytes()); uc = (HttpURLConnection) uc.getURL().openConnection(); Wandora.initUrlConnection(uc); uc.setRequestProperty ("Authorization", "Basic " + encoding); } tried = true; res = ((HttpURLConnection) uc).getResponseCode(); } } return uc; } }
4,496
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ImageBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/ImageBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * ImageBox.java * * Created on November 8, 2004, 6:01 PM */ package org.wandora.utils; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; //import com.sun.image.codec.jpeg.*; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; /** * * @author akivela */ public class ImageBox { /** Creates a new instance of ImageBox */ private ImageBox() { // Private } public static void makeThumbnail(String ins, String outs, int width, int height, int quality) throws Exception { // load image from INFILE BufferedImage image = null; try { URL url = new URL(ins); image = ImageIO.read(url); } catch (Exception e1) { if(ins.startsWith("file:")) { ins = IObox.getFileFromURL(ins); } // if(ins.startsWith("file:/")) { // ins = ins.substring(6); // } File imageFile = new File(ins); // remove prefix "file://" image = ImageIO.read(imageFile); } if(image != null) { // determine thumbnail size from WIDTH and HEIGHT int thumbWidth = width; int thumbHeight = height; double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // draw original image to thumbnail image object and // scale it to the new size on-the-fly BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // save thumbnail image to OUTFILE ImageWriter writer=ImageIO.getImageWritersByFormatName("jpeg").next(); IIOImage iioi=new IIOImage(thumbImage,null,null); ImageWriteParam param=writer.getDefaultWriteParam(); param.setCompressionMode(param.MODE_EXPLICIT); param.setCompressionQuality((float)quality / 100.0f); FileImageOutputStream output=new FileImageOutputStream(new File(outs)); writer.setOutput(output); writer.write(null,iioi,param); output.close(); /* BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outs)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float)quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); */ } } }
4,319
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MimeTypes.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/MimeTypes.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils; import java.io.File; import java.net.URL; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * This class contains mappings from common file extensions to their mime types. * Loads mimetypes from a class path file conf/mime.types. See one in Wandora's * conf folder for an example. * * @author olli */ public class MimeTypes { public static HashMap<String,String> extensionMap = new LinkedHashMap<String,String>(); static { try { String mimeContent = IObox.loadResource("conf/mime.types"); String[] mimeLines = mimeContent.split("\n"); for(int i=0; i<mimeLines.length; i++) { String mimeLine = mimeLines[i].trim(); if(mimeLine.length() == 0) continue; if(mimeLine.startsWith("#")) continue; String[] mimeParts = mimeLine.split("\\s"); if(mimeParts.length > 1) { String mimeType = mimeParts[0].trim(); if(mimeType.length() > 0) { for(int j=1; j<mimeParts.length; j++) { String fileExtension = mimeParts[j].trim(); if(fileExtension.length() > 0) { extensionMap.put(fileExtension, mimeType); // System.out.println(" "+mimeType+"\t\t"+fileExtension); } } } } } } catch (Exception e) { System.out.println("Exception '"+e.getMessage()+"' occurred while reading mime types from 'conf/mime.types'."); } /* extensionMap.put("ai","application/postscript"); extensionMap.put("aif","audio/x-aiff"); extensionMap.put("aifc","audio/x-aiff"); extensionMap.put("aiff","audio/x-aiff"); extensionMap.put("asc","text/plain"); extensionMap.put("atom","application/atom+xml "); extensionMap.put("au","audio/basic"); extensionMap.put("avi","video/x-msvideo"); extensionMap.put("bin","application/octet-stream"); extensionMap.put("c","text/plain"); extensionMap.put("cc","text/plain"); extensionMap.put("class","application/octet-stream"); extensionMap.put("csh","application/x-csh"); extensionMap.put("css","text/css"); extensionMap.put("doc","application/msword"); extensionMap.put("dvi","application/x-dvi"); extensionMap.put("eps","application/postscript"); extensionMap.put("exe","application/octet-stream"); extensionMap.put("fli","video/x-fli"); extensionMap.put("gif","image/gif"); extensionMap.put("gml","application/gml+xml"); extensionMap.put("gpx","application/gpx+xml"); extensionMap.put("gxf","application/gxf"); extensionMap.put("gtar","application/x-gtar"); extensionMap.put("gz","application/x-gzip"); extensionMap.put("htm","text/html"); extensionMap.put("html","text/html"); extensionMap.put("hqx","application/mac-binhex40"); extensionMap.put("ief","image/ief"); extensionMap.put("jar","application/java-archive"); extensionMap.put("ser","application/java-serialized-object"); extensionMap.put("class","application/java-vm"); extensionMap.put("jpe","image/jpeg"); extensionMap.put("jpeg","image/jpeg"); extensionMap.put("jpg","image/jpeg"); extensionMap.put("js","application/x-javascript"); extensionMap.put("json","application/json"); extensionMap.put("jsonml","application/jsonml+json"); extensionMap.put("latex","application/x-latex"); extensionMap.put("lha","application/octet-stream"); extensionMap.put("lsp","application/x-lisp"); extensionMap.put("lzh","application/octet-stream"); extensionMap.put("ma","application/mathematica"); extensionMap.put("mads","application/mads+xml"); extensionMap.put("man","application/x-troff-man"); extensionMap.put("mathml","application/mathml+xml"); extensionMap.put("mbox","application/mbox"); extensionMap.put("mrc","application/marc"); extensionMap.put("mrcx","application/marcxml+xml"); extensionMap.put("mesh","model/mesh"); extensionMap.put("mods","application/mods+xml"); extensionMap.put("mid","audio/midi"); extensionMap.put("midi","audio/midi"); extensionMap.put("mime","www/mime"); extensionMap.put("mov","video/quicktime"); extensionMap.put("movie","video/x-sgi-movie"); extensionMap.put("mp2","audio/mpeg"); extensionMap.put("mp3","audio/mpeg"); extensionMap.put("mpe","video/mpeg"); extensionMap.put("mpeg","video/mpeg"); extensionMap.put("mpg","video/mpeg"); extensionMap.put("mpga","audio/mpeg"); extensionMap.put("ms","application/x-troff-ms"); extensionMap.put("msh","model/mesh"); extensionMap.put("nc","application/x-netcdf"); extensionMap.put("ogx","application/ogg"); extensionMap.put("pbm","image/x-portable-bitmap"); extensionMap.put("pdf","application/pdf"); extensionMap.put("pgm","image/x-portable-graymap"); extensionMap.put("png","image/png"); extensionMap.put("pnm","image/x-portable-anymap"); extensionMap.put("pot","application/mspowerpoint"); extensionMap.put("ppm","image/x-portable-pixmap"); extensionMap.put("pps","application/mspowerpoint"); extensionMap.put("ppt","application/mspowerpoint"); extensionMap.put("ppz","application/mspowerpoint"); extensionMap.put("ps","application/postscript"); extensionMap.put("qt","video/quicktime"); extensionMap.put("ra","audio/x-realaudio"); extensionMap.put("ram","audio/x-pn-realaudio"); extensionMap.put("rdf","application/rdf+xml"); extensionMap.put("rgb","image/x-rgb"); extensionMap.put("rm","audio/x-pn-realaudio"); extensionMap.put("roff","application/x-troff"); extensionMap.put("rpm","audio/x-pn-realaudio-plugin"); extensionMap.put("rss","application/rss+xml"); extensionMap.put("rtf","text/rtf"); extensionMap.put("rtx","text/richtext"); extensionMap.put("sgm","text/sgml"); extensionMap.put("sgml","text/sgml"); extensionMap.put("sh","application/x-sh"); extensionMap.put("sit","application/x-stuffit"); extensionMap.put("smi","application/smil"); extensionMap.put("smil","application/smil"); extensionMap.put("snd","audio/basic"); extensionMap.put("swf","application/x-shockwave-flash"); extensionMap.put("tar","application/x-tar"); extensionMap.put("tcl","application/x-tcl"); extensionMap.put("tex","application/x-tex"); extensionMap.put("texi","application/x-texinfo"); extensionMap.put("texinfo","application/x-texinfo"); extensionMap.put("tif","image/tiff"); extensionMap.put("tiff","image/tiff"); extensionMap.put("tr","application/x-troff"); extensionMap.put("txt","text/plain"); extensionMap.put("unv","application/i-deas"); extensionMap.put("viv","video/vnd.vivo"); extensionMap.put("vivo","video/vnd.vivo"); extensionMap.put("vrml","model/vrml"); extensionMap.put("wav","audio/x-wav"); extensionMap.put("wrl","model/vrml"); extensionMap.put("xbm","image/x-xbitmap"); extensionMap.put("xlc","application/vnd.ms-excel"); extensionMap.put("xll","application/vnd.ms-excel"); extensionMap.put("xlm","application/vnd.ms-excel"); extensionMap.put("xls","application/vnd.ms-excel"); extensionMap.put("xlw","application/vnd.ms-excel"); extensionMap.put("xml","text/xml"); extensionMap.put("xpm","image/x-xpixmap"); extensionMap.put("zip","application/zip"); */ } public static HashMap<String,String> inverseMap = new LinkedHashMap<String,String>(); static { for(Map.Entry<String,String> e : extensionMap.entrySet()) { if(!inverseMap.containsKey(e.getValue())) { inverseMap.put(e.getValue(), e.getKey()); } } } public MimeTypes(){ } /** * Returns mime type for a file or extension. * @param file File name or just file extension. * @return */ public static String getMimeType(String file){ int ind=file.lastIndexOf("."); if(ind>-1) file=file.substring(ind+1); file=file.toLowerCase(); return extensionMap.get(file); } public static String getMimeType(File file){ return getMimeType(file.getAbsolutePath()); } public static String getMimeType(URL url){ return getMimeType(url.getPath()); } public static String getExtension(String mimeType){ return inverseMap.get(mimeType); } }
9,904
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
KeyedHashMap.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/KeyedHashMap.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TopicMapMap.java * * Created on 18. lokakuuta 2005, 14:14 */ package org.wandora.utils; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * <p> * A hash map where the key specified in the put and get methods is not really used as * the key but instead another object is derived from it which is then used as the key. * In some cases it would be useful to have the equals and hashCode methods behave * differently depending on the situation. For example you may * want to have the original behavior of equals method (that is the == check) but have * it check the actual contents of the object instead of object equality when you use it * as a key in a HashMap.</p> * <p> * To use this class you need to specify in constructor the function that transforms the key into * another object that has the new implementation for equals and hashCode methods. Typically * this object will wrap the original key and use some information in there. * Later you use get and put methods normally. The function transforming keys is * called automatically. * </p> * * * @author olli */ public class KeyedHashMap<K,V> implements Map<K,V> { protected HashMap<Wrapper<K>,V> map; protected Delegate<? extends Object,K> keyMaker; /** Creates a new instance of TopicMapMap */ public KeyedHashMap(Delegate<? extends Object,K> keyMaker) { this.keyMaker=keyMaker; map=new HashMap<Wrapper<K>,V>(); } public Wrapper getWrapper(K k){ return new Wrapper(k,keyMaker.invoke(k)); } public void clear(){ map.clear(); } public boolean containsKey(Object key){ return map.containsKey(getWrapper((K)key)); } public boolean containsValue(Object value){ return map.containsValue(value); } public Set<Map.Entry<K,V>> entrySet(){ HashSet<Map.Entry<K,V>> ret=new HashSet<Map.Entry<K,V>>(); for(Map.Entry<Wrapper<K>,V> e : map.entrySet()){ ret.add(new MapEntry<K,V>(e.getKey().wrapped,e.getValue())); } return ret; } public boolean equals(Object o){ if(o instanceof Map){ return entrySet().equals(((Map)o).entrySet()); } else return false; } public V get(Object key){ return map.get(getWrapper((K)key)); } public int hashCode(){ int code=0; for(Map.Entry<K,V> e : entrySet()){ code+=e.hashCode(); } return code; } public boolean isEmpty(){ return map.isEmpty(); } public Set<K> keySet(){ HashSet<K> ret=new HashSet<K>(); for(Map.Entry<Wrapper<K>,V> e : map.entrySet()){ ret.add(e.getKey().wrapped); } return ret; } public V put(K key,V value){ Wrapper<K> wrapper=getWrapper(key); if(wrapper.key==null) throw new NullPointerException("KeyedHashMap wrapper key is null"); return (V)map.put(wrapper,value); } public void putAll(Map<? extends K,? extends V> t){ for(Map.Entry e : t.entrySet()){ put((K)e.getKey(),(V)e.getValue()); } } public V remove(Object key){ return map.remove(getWrapper((K)key)); } public int size(){ return map.size(); } public Collection<V> values(){ return map.values(); } } class Wrapper<K> { public K wrapped; public Object key; public Wrapper(K wrapped,Object key){ this.wrapped=wrapped; this.key=key; } public int hashCode(){ if(key==null) return 0; return key.hashCode(); } public boolean equals(Object o){ if(o != null && o instanceof Wrapper && key != null) { return key.equals(((Wrapper)o).key); } else return false; } }
4,714
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HTTPServer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/HTTPServer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * HTTPServer.java * * Created on 6.6.2005, 14:54 * */ package org.wandora.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.Socket; import java.net.URLDecoder; import java.util.HashMap; import java.util.StringTokenizer; import javax.net.ssl.SSLServerSocketFactory; /** * For the ssl to work you need to create a certificate in command prompt with the * keytool utility (should be in jdk bin directory). * * For example: * keytool -genkey -keystore storefile -keyalg RSA * * After you have generated the certificate you need to run java with the following * parameters (or you may set the properties programmatically with System.setProperty): * -Djavax.net.ssl.keyStore=storefile -Djavax.net.ssl.keyStorePassword=password * * Every request is sent to handleRequest(Socket) which, after doing basic * authentication and parsing the requests, calls handleRequest(Socket,String). * It then calls the two abstract methods getPage and getContentType. * The most simple way to make a HTTPServer is to implement these two methods. * If you need to do more advanced handling you may also override one of the * handleRequest methods. * * @author olli */ public abstract class HTTPServer { protected int port; protected boolean running; protected boolean printExceptions; protected boolean useSSL; protected String loginUser; protected String loginPass; protected ServerSocket serverSocket; protected ServerThread serverThread; protected HashMap<String,String> mimeTypes; /** Creates a new instance of ScreenShotServer */ public HTTPServer(int port) { this.port=port; printExceptions=true; useSSL=false; mimeTypes=new HashMap<String,String>(); registerMimeTypes(); } protected void registerMimeTypes(){ mimeTypes.put("html","text/html"); mimeTypes.put("htm", "text/html"); mimeTypes.put("css", "text/css"); mimeTypes.put("txt", "text/plain"); mimeTypes.put("jpg", "image/jpg"); mimeTypes.put("jpeg","image/jpg"); mimeTypes.put("png", "image/png"); mimeTypes.put("gif", "image/gif"); mimeTypes.put("mp3", "audio/mpeg"); mimeTypes.put("mpg", "video/mpeg"); mimeTypes.put("mpeg","video/mpeg"); mimeTypes.put("avi", "video/x-msvideo"); mimeTypes.put("pdf", "application/pdf"); mimeTypes.put("zip", "application/zip"); } /** * Handles http request. Does simple authentication check if requiredCredentials * has been set. */ protected void handleRequest(Socket s) throws IOException { String credentials=null; String get=null; BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); String request=in.readLine(); while(request.trim().length()>0){ StringTokenizer st=new StringTokenizer(request); if(st.hasMoreTokens()){ String first=st.nextToken(); if(first.equals("Authorization:")){ if(!st.hasMoreTokens()) continue; st.nextToken(); if(!st.hasMoreTokens()) continue; credentials=st.nextToken(); } else if(first.equals("GET")){ if(!st.hasMoreTokens()) continue; get=st.nextToken(); } } request=in.readLine(); } String requiredCredentials=null; if(loginUser!=null) requiredCredentials=loginUser+":"+loginPass; if(requiredCredentials!=null){ boolean ok=false; if(credentials!=null){ byte[] bs=Base64.decode(credentials); String gotc=new String(bs); ok=requiredCredentials.equals(gotc); } if(!ok){ OutputStream out=s.getOutputStream(); out.write( ("HTTP/1.0 401 Authorization Required\nWWW-Authenticate: Basic realm=\""+getRealm()+"\"\n").getBytes() ); s.close(); return; } } handleRequest(s,get); } public String getRealm(){ return "Grip Realm"; } public static void copyStream(InputStream in,OutputStream out) throws IOException { byte[] buf=new byte[8192]; int read=-1; while((read=in.read(buf))!=-1){ out.write(buf,0,read); } } public void returnFile(OutputStream out,File f) throws IOException { if(!f.exists() || f.isDirectory()){ notFound(out); return; } writeHeaderForFile(out,f); InputStream in=new FileInputStream(f); copyStream(in,out); in.close(); } public void writeHeaderForFile(OutputStream out,String extension) throws IOException { String type=null; if(extension!=null) type=mimeTypes.get(extension.toLowerCase()); if(type==null) type="text/plain"; writeHeader(out,type); } public void writeHeaderForFile(OutputStream out,File f) throws IOException { String name=f.getName(); int ind=name.lastIndexOf("."); if(ind==-1) writeHeaderForFile(out,(String)null); else writeHeaderForFile(out,name.substring(ind+1)); } public static void writeHTMLHeader(OutputStream out) throws IOException { writeHeader(out,"text/html"); } public static void writeHeader(OutputStream out,String contentType) throws IOException { out.write( "HTTP/1.0 200 OK\n".getBytes() ); out.write( ("Content-Type: "+contentType+"\n\n").getBytes() ); } public static void writeSimpleHTML(OutputStream out,String title,String content) throws IOException { writeHTMLHeader(out); String page="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"+ "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"+ (title!=null?"<title>"+title+"</title>":"")+ "</head><body>"+content+"</body></html>"; try{ out.write(page.getBytes("UTF-8")); }catch(UnsupportedEncodingException uee){} } public static void writeInternalServerError(OutputStream out,String message,Throwable t) throws IOException { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); p.flush(); writeSimpleHTML(out,"500 Internal Server Error","500 Internal Server Error<br />"+(message!=null?message+"<br />":"")+"<pre>"+s.toString()+"</pre>"); } /** * Handles the request by getting the contents of the page using getPage. * Then writes the header and the contents and closes socket. */ protected void handleRequest(Socket s,String get) throws IOException { String[] parameters=parseGetParams(get); OutputStream out=s.getOutputStream(); if(!getPage(out,parameters)){ notFound(out); } s.close(); } /** * Gets the contents of the page for the given request. */ protected abstract boolean getPage(OutputStream out,String[] parameters); /** * Parses parameters from url. * @return A String array where first element is the requested page and after that * every odd index contains a parameter key and * every even index value for previous key. */ public static String[] parseGetParams(String get){ try{ int ind=get.indexOf("?"); if(ind==-1) return new String[]{URLDecoder.decode(get,"UTF-8")}; String query=get.substring(0,ind); String[] params=get.substring(ind+1).split("&"); String[] ret=new String[params.length*2+1]; ret[0]=URLDecoder.decode(query,"UTF-8"); for(int i=0;i<params.length;i++){ String key=null; String value=null; ind=params[i].indexOf("="); if(ind==-1) key=params[i]; else { key=params[i].substring(0,ind); value=params[i].substring(ind+1); } if(key!=null) key=URLDecoder.decode(key,"UTF-8"); if(value!=null) value=URLDecoder.decode(value,"UTF-8"); ret[1+i*2]=key; ret[1+i*2+1]=value; } return ret; }catch(UnsupportedEncodingException e){ e.printStackTrace(); return null; } } /** * A convenience method to respond with a not found message. */ public static void notFound(OutputStream out) throws IOException { out.write( "HTTP/1.0 404 Not Found\n\n404 Not Found.".getBytes() ); } public static void badRequest(OutputStream out) throws IOException { out.write( "HTTP/1.0 400 Bad Request\n\n400 Bad Request.".getBytes() ); } /** * Returns the first parameter value with the given key. * @param param The key of the param to find. * @param params The parameters as returned by parseGetParams. * @return The first parameter value with the given key or null if non is found. */ public static String getParamValue(String param,String[] params){ for(int i=1;i<params.length;i+=2){ if(params[i].equals(param)) return params[i+1]; } return null; } public void setPrintExceptions(boolean value){ printExceptions=value; } public int getPort(){return port;} public void setPort(int p){port=p;} /** * Set credential required to use the server. If user is null or empty string, * allows anonymous login. */ public void setLogin(String user,String password){ if(user==null || user.length()==0) { loginUser=null; loginPass=null; } else { loginUser=user; loginPass=password; } } public String getLoginUser(){return loginUser;} public String getLoginPassword(){return loginPass;} /** * Enables or disables use of SSL sockets. You must set this before * starting the server. See notes in the class description about * configuring SSL. */ public void setUseSSL(boolean value){ useSSL=value; } public boolean isUseSSL(){return useSSL;} /** * Starts the server. If server is already running, stops it first. */ public void start(){ stopServer(); running=true; serverThread=new ServerThread(); serverThread.start(); } public boolean isRunning(){return running;} /** * Stops the server and waits for the server thread to die before returning. */ public void stopServer(){ if(serverThread==null) return; boolean oldPrint=printExceptions; printExceptions=false; running=false; try{ while(serverThread.isAlive()){ if(!serverSocket.isClosed()) serverSocket.close(); try{ serverThread.join(); }catch(InterruptedException ie){} } }catch(IOException ioe){} printExceptions=oldPrint; serverThread=null; } private class ServerThread extends Thread { @Override public void run() { try{ if(!useSSL){ serverSocket=new ServerSocket(port); } else{ serverSocket=SSLServerSocketFactory.getDefault().createServerSocket(port); } while(running){ try{ final Socket s=serverSocket.accept(); Thread t=new Thread(){ @Override public void run(){ try{ handleRequest(s); }catch(Exception e){ if(printExceptions) e.printStackTrace(); } } }; t.start(); } catch(Exception e){ if(printExceptions) e.printStackTrace(); } } if(!serverSocket.isClosed()) serverSocket.close(); }catch(Exception e){ if(printExceptions) e.printStackTrace(); } serverSocket=null; } } }
13,951
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XMLParamProcessor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/XMLParamProcessor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * XMLParamProcessor.java * * Created on 1.6.2004, 12:51 */ package org.wandora.utils; import java.io.File; import java.io.InputStream; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * <p> * Utility to create Java Objects from xml. Recursively creates or retrieves objects from symbol table * for constructor and method parameters. With some helper classes inserted into the symbol table beforehand, * can be pretty much used to execute arbitrary Java code. Normally parameters to class constructors are * parsed recursively from the child elements of the creating element. Your class can however implement * <code>XMLParamAware</code> in which case your class will be provided with the DOM element and you can implement custom * parameter parsing. <code>XMLParamAware</code> clasesses are also given this <code>XMLParamProcessor</code> so they have access to the * entire symbol table created (at the time of their generation). So parameters can also be passed by putting objects * in the symbol table with specific keys. This is especially usefull for objects that are passed to allmost * every object (such as loggers; which many classes will try to get from symbol table with key "logger").</p> * <p> * New objects are usually created by providing the full class name of the created object. You can also map * element names to different classes beforehand and then create new objects with these element names.</p> * <ul> * <li>id attribute specifies the id of the created or returned object in the symbol table. If the symbol table * allready contains an object with the given id, it is overwritten.</li> * <li>idref attribute specifies the id of the object to be retrieved from the symbol table.</li> * <li>class attribute specifies the full class name of the object to be created.</li> * <li>array attribute specifies the full class name of the component type of the array to be created.</li> * <li>method attribute specifies the name of the method to execute.</li> * <li>literal attribute specifies whether the contents of the element should be interpreted as a literal string. * Possible values true and false, default is false.</li> * </ul></p> * <p> * Only one of the idref, class, array and static attributes can be specified. This determines how to create or * retrieve the object. The value of idref must be the id of the object in the symbol table, the value of the * other three must be a full class name. With idref you can use either method or field attribute to invoke a method * or get the value of a field respectively and with static you must use one of these. * <ul> * <li>When class is used, a new object is created and child elements are used as constructor parameters.</li> * <li>When array is used, a new array object is created and child elements are used to populate the array.</li> * <li>When idref is used, object is retrieved from the symbol table.</li> * <li>When static is used, the resulting object is the return value of a static method or the value of a static field.</li> * <li>When none of the above are specified * <ol> * <li>If the used element name has been mapped to a class, this mapping will be used to create a new instance of * the class as if class attribute were used. The following mappings are used by default * <ul> * <li>string => java.lang.String</li> * <li>integer => java.lang.Integer</li> * <li>double => java.lang.Double</li> * <li>boolean => java.lang.Boolean</li> * <li>properties => org.wandora.piccolo.XMLProperties</li></ul></li> * <li>If that fails, class attribute is treated to be "java.lang.String" and literal is forced to true.</li> * <ol></li> * </ul></p> * <p> * When you use class attribute to create a new object, note that the class you are creating might implement * XMLParamAware, in which case refer to the documentation of that class about how the child elements are used. * You must use either method or field attribute when using static. * <ul> * <li>Using the method attribute will cause the invokation of the specified method with the parameters read from the child elements * except when it is used with class attribute, in which case the method is called without parameters.</li> * <li>Using the field attribute will get the specified field of the object.</li> * <li>When id attribute is specified, the created object or the object returned by the method call or the object retrieved from the symbol table is * assigned into the symbol table with the specified id. Also the used element name is stored and can be retrieved with getObjectType method.</li> * <li>literal attribute is used to create String objects from the contents of the element.</li> * </ul></p> * <p> * For example, consider the following xml: * <code><pre> * &lt;object id="p" class="Store"> * &lt;param class="java.lang.String" literal="true">Store name&lt;/param> * &lt;param array="StoreItem"> * &lt;item class="StoreItem"> * &lt;param class="java.lang.String" literal="true">apple&lt;/param> * &lt;param class="java.lang.Integer" literal="true">5&lt;/param> * &lt;/item> * &lt;item class="StoreItem"> * &lt;String>banana&lt;/String> * &lt;Integer>10&lt;/Integer> * &lt;/item> * &lt;/param> * &lt;/object> * &lt;object id="customer" class="Customer"/> * &lt;method id="error" idref="p" method="buyOne"> * &lt;param idref="customer"/> * &lt;param class="java.lang.String">apple&lt;/param> * &lt;/method> * </pre></code> * <p> * This would roughly be equivalent to the following java code:<br> * <code><pre> * Store p=new Store("Store name",new StoreItem[]{new StoreItem("apple",5),new StoreItem("banana",10)}); * Customer customer=new Customer(); * Boolean error=p.buyOne(customer,"apple"); * </pre></code> * Note that the first StoreItem is created using the full syntax and the second item shows how to use the * shorter syntax for java.lang.* classes.</p> * <p> * As another example, the following is pretty much equal to <code>System.out.println("Hello World");</code> (note the use of * name space). * <code><pre> * &lt;root xmlns:xp="http://wandora.org/xmlparamprocessor"> * &lt;object xp:id="out" xp:static="java.lang.System" xp:field="out"/> * &lt;method xp:idref="out" xp:method="println"> * &lt;param xp:class="java.lang.String" xp:literal="true">Hello World!&lt;/param> * &lt;/method> * &lt;/root> * </pre></code></p> * <p> * Note the autoboxing/unboxing of primitive types. However, the symbol table will only contain Objects, that * is no primitive types. * Also note that String,Integer,Double,Boolean etc all have a constructor accepting a single String parameter * thus the creation of Integers with literal attribute set to true works (as does the shorter syntax using Integer * element name). * Note that arithmetic operations are not directly possible. However you could make an object into the symbol * table which provides the necessary methods.</p> * <p> * To use <code>XMLParamProcessor</code>, first create a new instance of it. * Then add whatever objects you want to the symbol table (optional). * Then use <code>processElement</code> or one of the create methods to process elements of the XML. * Finally you can get objects from the symbol table if you need to.</p> * <p> * You can use getObjectType to get the element name used to create the object. This way you can easily * group your objects into different categories.</p> * <p> * Note that by default <code>XMLParamProcessor</code> uses a namespace "http://wandora.org/xmlparamprocessor" for * all the attributes. So either use setNameSpace method to set the name space to null to disable this or take * care that your xml has proper name spaces setup and that the xml implementation supports name spaces. * You should use javax.xml.parsers.DocumentBuilderFactory.setNamespaceAware(true) before creating the * document builder used to parse the document.</p> * * @see XMLParamAware * @author olli */ public class XMLParamProcessor { /** * The default namespace URI. */ public static final String DEFAULT_NAMESPACE="http://www.gripstudios.com/xmlparamprocessor"; private HashMap objectTable; private HashMap objectTypeTable; private String nameSpace; private HashMap classMap; private HashSet forcedLiterals; /** Creates a new instance of XMLParamProcessor */ public XMLParamProcessor() { objectTable=new HashMap(); objectTypeTable=new HashMap(); classMap=new HashMap(); nameSpace=DEFAULT_NAMESPACE; addObjectToTable("this",this); mapClass("integer","java.lang.Integer"); mapClass("string","java.lang.String"); mapClass("boolean","java.lang.Boolean"); mapClass("double","java.lang.Double"); mapClass("properties","org.wandora.piccolo.XMLProperties"); forcedLiterals=new HashSet(); forcedLiterals.add("integer"); forcedLiterals.add("string"); forcedLiterals.add("boolean"); forcedLiterals.add("double"); } /** * Sets the used name space URI. * @param ns The new name space URI or null to disable the use of name spaces. */ public void setNameSpace(String ns){ nameSpace=ns; } /** * Reset the whole symbol table. * @param table The new symbol table. Should contain id Strings mapped to the corresponding objects. */ public void setSymbolTable(HashMap table){ objectTable=table; } /** * Map a given node name to a specific class. If className is null, removes the previous association. * After a node name N is mapped to class C, an element with node name N will behave as if it had * attribute class with value C. Thus if you create many instances of the same class, you can map * a specific node name to that class after which you don't need to write the class attribute for * every element. */ public void mapClass(String nodeName,String className){ if(className==null) classMap.remove(nodeName); else classMap.put(nodeName,className); } public String getClassMapping(String nodeName){ return (String)classMap.get(nodeName); } /** * Adds (or reassigns) a single object to the symbol table. * @param id The id of the object. * @param o The object to be assigned with the given id. */ public void addObjectToTable(String id,Object o){ objectTable.put(id,o); } /** * Gets an object from the symbol table. * @param id The id of the object to get. * @return The object or null if not found (or the object really is null). */ public Object getObject(String id){ return objectTable.get(id); } public String getObjectType(String id){ return (String)objectTypeTable.get(id); } /** * Returns the whole symbol table. * @return The symbol table with ids mapped to objects. */ public HashMap getSymbolTable(){ return objectTable; } public static Class[] getTypeArray(Object[] params){ Class[] paramTypes=new Class[params.length]; for(int i=0;i<paramTypes.length;i++) paramTypes[i]=params[i].getClass(); return paramTypes; } public static boolean isInstanceOrBoxed(Class type,Object param){ if(param==null) return !type.isPrimitive(); if(type.isInstance(param)) return true; Class pclass=param.getClass(); if(type.isPrimitive()){ if(type.equals(Boolean.TYPE) && pclass.equals(Boolean.class)) return true; if(type.equals(Character.TYPE) && pclass.equals(Character.class)) return true; if(type.equals(Byte.TYPE) && pclass.equals(Byte.class)) return true; if(type.equals(Short.TYPE) && pclass.equals(Short.class)) return true; if(type.equals(Integer.TYPE) && pclass.equals(Integer.class)) return true; if(type.equals(Long.TYPE) && pclass.equals(Long.class)) return true; if(type.equals(Float.TYPE) && pclass.equals(Float.class)) return true; if(type.equals(Double.TYPE) && pclass.equals(Double.class)) return true; } return false; } public static Constructor findConstructor(Class cls,Object[] params) throws Exception { Constructor[] cs=cls.getConstructors(); Outer: for(int i=0;i<cs.length;i++){ // if(!cs[i].isAccessible()) continue; Class[] types=cs[i].getParameterTypes(); if(types.length!=params.length) continue; for(int j=0;j<types.length;j++){ // if(!types[j].isInstance(params[j])) continue Outer; if(!isInstanceOrBoxed(types[j],params[j])) continue Outer; } return cs[i]; } return null; } public static Method findMethod(Class cls,String method,Object[] params) throws Exception { Method[] ms=cls.getMethods(); Outer: for(int i=0;i<ms.length;i++){ if(!ms[i].getName().equals(method)) continue; // if(!ms[i].isAccessible()) continue; Class[] types=ms[i].getParameterTypes(); if(types.length!=params.length) continue; for(int j=0;j<types.length;j++){ // if(!types[j].isInstance(params[j])) continue Outer; if(!isInstanceOrBoxed(types[j],params[j])) continue Outer; } return ms[i]; } return null; } private String getAttribute(Element e,String attr){ if(nameSpace!=null) return e.getAttributeNS(nameSpace,attr); else return e.getAttribute(attr); } public static String getNodeContents(Node n){ short type=n.getNodeType(); if(type==Node.TEXT_NODE) return n.getNodeValue(); else if(type==Node.CDATA_SECTION_NODE) return n.getNodeValue(); else if(type==Node.ELEMENT_NODE){ StringBuffer buf=new StringBuffer(); NodeList nl=n.getChildNodes(); for(int i=0;i<nl.getLength();i++){ buf.append(getNodeContents(nl.item(i))); } return buf.toString(); } else return ""; } public static String getElementContents(Element e){ return getNodeContents(e); /* NodeList nl=e.getChildNodes(); StringBuffer s=new StringBuffer(); for(int i=0;i<nl.getLength();i++){ Node n=nl.item(i); String v=n.getNodeValue(); if(v!=null) s.append(v); } return s.toString();*/ } /** * Interprets one element and returns the created or retrieved object. Also interpretes any parameters * (child nodes) the interpration of the actual element might require. Adds objects to symbol table * where elements contain id attribute. * @param e The element to interpret. * @return The created object, the retrieved object or the result of the method call or null if the symbol * table didn't contain the object or the method call returns null. */ public Object createObject(Element e) throws Exception { return createObject(e,null); } public Object createObject(Element e,String forceClass) throws Exception { String idref=getAttribute(e,"idref"); String id=getAttribute(e,"id"); String array=getAttribute(e,"array"); String cls=getAttribute(e,"class"); if(forceClass!=null) cls=forceClass; String method=getAttribute(e,"method"); String field=getAttribute(e,"field"); String literal=getAttribute(e,"literal"); String stc=getAttribute(e,"static"); if(idref.length()>0 || stc.length()>0){ Object o=null; Class c=null; if(idref.length()>0){ if(idref.equals("null")){ o=null; c=null; } else{ o=objectTable.get(idref); if(o==null) throw new Exception("invalid object id :\""+idref+"\""); c=o.getClass(); } } else{ c=Class.forName(stc); o=null; if(field.length()==0 && method.length()==0) throw new Exception("Can't use static class "+stc+" without filed or method."); } if(field.length()>0){ Object r=c.getField(field).get(o); if(id.length()>0) { objectTable.put(id,r); objectTypeTable.put(id,e.getNodeName()); } return r; } else if(method.length()>0){ Object[] params=createArray(e,new Object[0]); Method m=findMethod(c,method,params); if(m==null) throw new NoSuchMethodException(o.getClass().getName()+"."+method); Object r=m.invoke(o,params); if(id.length()>0){ objectTable.put(id,r); objectTypeTable.put(id,e.getNodeName()); } return r; } else{ if(id.length()>0){ objectTable.put(id,o); objectTypeTable.put(id,e.getNodeName()); } return o; } } else if(array.length()>0){ Object arrayType=Array.newInstance(Class.forName(array),0); Object a=createArray(e,(Object[])arrayType); if(id.length()>0) objectTable.put(id,a); return a; } else{ if(cls.length()==0){ String nname=e.getNodeName(); if(classMap.get(nname)!=null){ cls=(String)classMap.get(nname); if(forcedLiterals.contains(nname)) literal="true"; } else{ /* nname=nname.toLowerCase(); nname=nname.substring(0,1).toUpperCase()+nname.substring(1); try{ Class.forName("java.lang."+nname); cls="java.lang."+nname; }catch(ClassNotFoundException ex){ cls="java.lang.String"; }*/ cls="java.lang.String"; literal="true"; } } boolean aware=false; Class c=Class.forName(cls); Class[] ints=c.getInterfaces(); for(int i=0;i<ints.length;i++){ if(ints[i]==XMLParamAware.class){ aware=true; break; } } Object o; if(!aware){ Object[] params; if(literal.equalsIgnoreCase("true")){ String s=getElementContents(e); params=new Object[]{s}; } else{ params=createArray(e,new Object[0]); } Constructor constructor=findConstructor(c,params); if(constructor==null) throw new NoSuchMethodException(cls+".<init>"); o=constructor.newInstance(params); } else{ Constructor constructor=c.getConstructor(new Class[0]); if(constructor==null) throw new NoSuchMethodException(cls+".<init>"); o=constructor.newInstance(new Object[]{}); ((XMLParamAware)o).xmlParamInitialize(e,this); } if(field.length()>0){ o=o.getClass().getField(field).get(o); } else if(method.length()>0){ Object[] params=new Object[0]; Method m=findMethod(o.getClass(),method,params); if(m==null) throw new NoSuchMethodException(o.getClass().getName()+"."+method); o=m.invoke(o,params); } if(id.length()>0){ objectTable.put(id,o); objectTypeTable.put(id,e.getNodeName()); } return o; } } /** * Creates an array of the child nodes of the given element. This is equivalent to calling * createObject for each child element of the given element, and putting the results in an * array. The returned array will have the type or arrayType or Object[] if arrayType is null. * @param e The element whose child elements are parsed. * @param arrayType An object used to determine the type of the returned array. If null, the returned * array will be of type Object[]. * @return The created array. */ public Object[] createArray(Element e,Object[] arrayType) throws Exception { NodeList nl=e.getChildNodes(); ArrayList al=new ArrayList(); for(int i=0;i<nl.getLength();i++){ Node n=nl.item(i); if(n instanceof Element){ al.add(createObject((Element)n)); } } if(arrayType==null) return al.toArray(); else return al.toArray(arrayType); } /** * Processes all the child elements of the given element. First (non null) element is returned * and the processing might * add objects to the symbol table which can then be retrieved there. * @param e The element whose child elements are parsed. */ public Object processElement(Element e) throws Exception { // createArray(e,null); Object first=null; NodeList nl=e.getChildNodes(); for(int i=0;i<nl.getLength();i++){ Node n=nl.item(i); if(n instanceof Element){ if(first==null) first=createObject((Element)n); else createObject((Element)n); } } return first; } /** * A convenience method to parse a Document from a File. The returned document * should support name spaces. */ public static Document parseDocument(String file) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); return builder.parse(new File(file)); } /** * A convenience method to parse a Document from a File. The returned document * should support name spaces. */ public static Document parseDocument(InputStream in) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); return builder.parse(in); } /** * A test main method. Parses the file given as the first command line parameter. */ public static void main(String[] args) throws Exception { Element doc=parseDocument(args[0]).getDocumentElement(); XMLParamProcessor processor=new XMLParamProcessor(); processor.createArray(doc,null); } }
24,555
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SQLProxyException.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/sqlproxy/SQLProxyException.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SQLProxyException.java * * Created on 13. lokakuuta 2006, 14:22 * */ package org.wandora.utils.sqlproxy; /** * * @author olli */ public class SQLProxyException extends Exception { /** Creates a new instance of SQLProxyException */ public SQLProxyException() { } public SQLProxyException(String message){ super(message); } }
1,181
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SQLProxyClient.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/sqlproxy/SQLProxyClient.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SQLProxyClient.java * * Created on 12. lokakuuta 2006, 13:08 * */ package org.wandora.utils.sqlproxy; import static org.wandora.utils.Tuples.t2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PushbackReader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.Socket; import java.sql.Types; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Vector; import java.util.zip.GZIPInputStream; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import org.wandora.utils.Tuples.T2; /** * * @author olli */ public class SQLProxyClient { private boolean useSSL=false; private Socket socket; private Writer outWriter; private PushbackReader inReader; private String charset="UTF-8"; private boolean compress=false; private String databaseFlavour="generic"; /** Creates a new instance of SQLProxyClient */ public SQLProxyClient() { } /** * sqlproxy:hostname[:port][/database][?param1=value1&param2=value2] * * params: * compress[=true|false] (default false, if param is specified without value, true is assumed) * flavour=mysql|generic (note this is not actually used in any way in SQLProxyClient, only stored for application use) * usessl[=true|false] (default false, if param is specified without value, true is assumed) */ public static SQLProxyClient createProxy(String connectionString,String user,String password) throws IOException,SQLProxyException { if(!connectionString.startsWith("sqlproxy:")) return null; connectionString=connectionString.substring("sqlproxy:".length()); if(connectionString.startsWith("//")) connectionString=connectionString.substring(2); int ind=connectionString.indexOf("?"); String params=""; String server=connectionString; if(ind>=0) { params=connectionString.substring(ind+1); server=connectionString.substring(0,ind); } String database="default"; ind=server.indexOf("/"); if(ind>=0){ database=server.substring(ind+1); server=server.substring(0,ind); } int port=SQLProxyServer.defaultPort; ind=server.indexOf(":"); if(ind>=0){ port=Integer.parseInt(server.substring(ind+1)); server=server.substring(0,ind); } String flavour="generic"; boolean compress=false; boolean useSSL=false; String[] split=params.split("&"); for(int i=0;i<split.length;i++){ String key=split[i]; String value=""; ind=key.indexOf("="); if(ind>=0){ value=key.substring(ind+1); key=key.substring(0,ind); } try{ key=java.net.URLDecoder.decode(key,"UTF-8"); value=java.net.URLDecoder.decode(value,"UTF-8"); }catch(UnsupportedEncodingException uee){uee.printStackTrace();} if(key.equals("compress")){ if(value.equalsIgnoreCase("false") || value.equals("0") || value.equalsIgnoreCase("no")) compress=false; else compress=true; } else if(key.equals("flavour")){ flavour=value; } else if(key.equals("usessl")){ if(value.equalsIgnoreCase("false") || value.equals("0") || value.equalsIgnoreCase("no")) useSSL=false; else useSSL=true; } else if(key.equals("user")){ user=value; } else if(key.equals("password")){ password=value; } } SQLProxyClient sqlProxy=new SQLProxyClient(); sqlProxy.setUseSSL(useSSL); sqlProxy.setFlavour(flavour); sqlProxy.connect(server,port); if(compress) sqlProxy.compress(); if(user!=null && user.length()>0) sqlProxy.login(user,password); sqlProxy.open(database); return sqlProxy; } public String getFlavour(){return databaseFlavour;} public void setFlavour(String f){this.databaseFlavour=f;} public void connect(String host) throws IOException { connect(host,SQLProxyServer.defaultPort,this.useSSL); } public void connect(String host,int port) throws IOException { connect(host,port,false); } public void connect(String host,int port,boolean useSSL) throws IOException { if(useSSL){ socket=SSLSocketFactory.getDefault().createSocket(host,port); } else{ socket=SocketFactory.getDefault().createSocket(host,port); } inReader=new PushbackReader(new InputStreamReader(socket.getInputStream(),charset)); outWriter=new OutputStreamWriter(socket.getOutputStream(),charset); } public void close() throws IOException { socket.close(); } public void setUseSSL(boolean b){ this.useSSL=b; } private String readLine() throws IOException { int c=-1; boolean escape=false; StringBuffer buf=new StringBuffer(); while( (c=inReader.read())!=-1 ){ if(!escape && c=='\\') escape=true; else { if(!escape && c=='\n') break; if(!escape && c=='\r') continue; else buf.append((char)c); escape=false; } } return buf.toString(); } private T2<String,Boolean> readString() throws IOException,SQLProxyException { int c=inReader.read(); if(c=='"'){ boolean escape=false; StringBuffer buf=new StringBuffer(); while( (c=inReader.read())!=-1 ){ if(!escape && c=='\\') escape=true; else { if(!escape && c=='\"') break; else buf.append((char)c); escape=false; } } while( (c=inReader.read())!=-1 ){ if(c==',') return t2(buf.toString(),false); else if(c=='\n') return t2(buf.toString(),true); } return t2(buf.toString(),true); } else if(c=='n'){ if(inReader.read()=='u' && inReader.read()=='l' && inReader.read()=='l') { while( (c=inReader.read())!=-1 ){ if(c==',') return t2(null,false); else if(c=='\n') return t2(null,true); } return t2(null,true); } } throw new SQLProxyException("Unexpected response"); } private T2<Integer,Boolean> readInteger() throws IOException,SQLProxyException { StringBuffer buf=new StringBuffer(); boolean eol=false; int c=-1; while( (c=inReader.read())!=-1 ){ if(c==',') { eol=false; break; } else if(c=='\n'){ eol=true; break; } else if(c=='\r') continue; else buf.append((char)c); } String s=buf.toString(); if(s.trim().equals("null")) return t2(null,eol); try{ int i=Integer.parseInt(s); return t2(i,eol); } catch(NumberFormatException nfe){ throw new SQLProxyException("Number format exception"); } } private T2<Double,Boolean> readDouble() throws IOException,SQLProxyException { StringBuffer buf=new StringBuffer(); boolean eol=false; int c=-1; while( (c=inReader.read())!=-1 ){ if(c==',') { eol=false; break; } else if(c=='\n'){ eol=true; break; } else if(c=='\r') continue; else buf.append((char)c); } String s=buf.toString(); if(s.trim().equals("null")) return t2(null,eol); try{ double d=Double.parseDouble(s); return t2(d,eol); } catch(NumberFormatException nfe){ throw new SQLProxyException("Number format exception"); } } private Collection<Map<String,Object>> readResultSet() throws IOException,SQLProxyException { String line=readLine(); if(!line.equals(SQLProxyServer.RES_RESULTSET)) throw new SQLProxyException("Unexpected return type "+line); line=readLine(); String[] parsed=line.split(","); int columnCount=parsed.length/2; String[] columnNames=new String[columnCount]; int[] columnTypes=new int[columnCount]; for(int i=0;i<parsed.length;i+=2){ columnNames[i/2]=parsed[i]; columnTypes[i/2]=Integer.parseInt(parsed[i+1]); } Vector<Map<String,Object>> result=new Vector<Map<String,Object>>(); while( true ){ int c=inReader.read(); if(c=='\r') continue; else if(c=='\n') break; else inReader.unread(c); Map<String,Object> row=new HashMap<String,Object>(); for(int i=0;i<columnCount;i++){ switch(columnTypes[i]){ case Types.BIGINT: case Types.BIT: case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT:{ T2<Integer,Boolean> r=readInteger(); row.put(columnNames[i],r.e1); break; } case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.NUMERIC: case Types.REAL: { T2<Double,Boolean> r=readDouble(); row.put(columnNames[i],r.e1); break; } default: { T2<String,Boolean> r=readString(); row.put(columnNames[i],r.e1); break; } } } result.add(row); } return result; } public int readUpdateCount() throws IOException, SQLProxyException { String line=readLine(); if(!line.equals(SQLProxyServer.RES_COUNT)) throw new SQLProxyException("Unexpected return type "+line); line=readLine(); try{ int i=Integer.parseInt(line); readLine(); return i; }catch(NumberFormatException nfe){ throw new SQLProxyException("Number format exception"); } } public synchronized void compress() throws IOException,SQLProxyException { outWriter.write("compress\n"); outWriter.flush(); compress=true; } public synchronized boolean login(String user,String pass) throws IOException { outWriter.write("login "+user+":"+pass+"\n"); outWriter.flush(); if(compress) inReader=new PushbackReader(new InputStreamReader(new GZIPInputStream(socket.getInputStream()),charset)); String line=readLine(); boolean ret=false; if(line.equals(SQLProxyServer.RES_OK)) ret=true; if(compress) finishCompressedStream(); return ret; } public synchronized boolean open(String database) throws IOException { outWriter.write("open "+database+"\n"); outWriter.flush(); if(compress) inReader=new PushbackReader(new InputStreamReader(new GZIPInputStream(socket.getInputStream()),charset)); String line=readLine(); boolean ret=false; if(line.equals(SQLProxyServer.RES_OK)) ret=true; if(compress) finishCompressedStream(); return ret; } public synchronized void executeCommand(String cmd) throws IOException,SQLProxyException { outWriter.write(cmd+"\n"); outWriter.flush(); } private void finishCompressedStream() throws IOException { while(inReader.read()!=-1) ; } public synchronized Collection<Map<String,Object>> executeQuery(String query) throws IOException,SQLProxyException { outWriter.write(query+"\n"); outWriter.flush(); if(compress) inReader=new PushbackReader(new InputStreamReader(new GZIPInputStream(socket.getInputStream()),charset)); Collection<Map<String,Object>> ret=readResultSet(); if(compress) finishCompressedStream(); return ret; } public synchronized int executeUpdate(String update) throws IOException,SQLProxyException { System.out.println("Executing proxy update "+update); outWriter.write(update+"\n"); outWriter.flush(); if(compress) inReader=new PushbackReader(new InputStreamReader(new GZIPInputStream(socket.getInputStream()),charset)); int ret=readUpdateCount(); if(compress) finishCompressedStream(); return ret; } public static void main(String[] args) throws Exception { String connectionString="sqlproxy:"; // String connectionString="sqlproxy:localhost/default?user=test&password=aaa&compress"; if(args.length>0) connectionString=args[0]; SQLProxyClient client=SQLProxyClient.createProxy(connectionString,null,null); BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); while(true){ String line=reader.readLine(); if(line.equalsIgnoreCase("quit")) { client.executeCommand("quit"); break; } Collection<Map<String,Object>> res=client.executeQuery(line); for(Map<String,Object> row : res){ boolean first=true; for(Map.Entry<String,Object> e : row.entrySet()){ if(!first) System.out.print(", "); first=false; System.out.print(e.getKey()+"=>"+e.getValue()); } System.out.println(); } } client.close(); } }
15,164
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SQLProxyServer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/sqlproxy/SQLProxyServer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SQLProxyServer.java * * Created on 12. lokakuuta 2006, 13:08 * */ package org.wandora.utils.sqlproxy; import static org.wandora.utils.Tuples.t4; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.ServerSocket; import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.HashMap; import java.util.zip.GZIPOutputStream; import javax.net.ssl.SSLServerSocketFactory; import org.wandora.utils.Tuples.T4; /** * * @author olli */ public class SQLProxyServer extends Thread { private boolean useSSL=false; public static final int defaultPort=8891; private int port; private boolean running=false; private boolean printExceptions=true; private boolean verbose=false; private boolean echo=false; private String credentials=null; private HashMap<String,T4<String,String,String,String>> connections; /** Creates a new instance of SQLProxyServer */ public SQLProxyServer(String dbDriver,String dbConnectionString,String dbUser,String dbPassword, String proxyUser, String proxyPassword) { this(dbDriver,dbConnectionString,dbUser,dbPassword,defaultPort); setCredentials(proxyUser + ":" + proxyPassword); } public SQLProxyServer(String dbDriver,String dbConnectionString,String dbUser,String dbPassword) { this(dbDriver,dbConnectionString,dbUser,dbPassword,defaultPort); } public SQLProxyServer(String dbConnectionString,String dbUser,String dbPassword) { this(null,dbConnectionString,dbUser,dbPassword,defaultPort); } public SQLProxyServer(String dbDriver,String dbConnectionString,String dbUser,String dbPassword,int port) { this(port); addConnection("default",dbDriver,dbConnectionString,dbUser,dbPassword); } public SQLProxyServer(String dbDriver,String dbConnectionString,String dbUser,String dbPassword,int port, String proxyUser, String proxyPassword) { this(port); setCredentials(proxyUser + ":" + proxyPassword); addConnection("default",dbDriver,dbConnectionString,dbUser,dbPassword); } public SQLProxyServer(String dbDriver,String dbConnectionString,String dbUser,String dbPassword,Integer port, String proxyUser, String proxyPassword) { this(port.intValue()); setCredentials(proxyUser + ":" + proxyPassword); addConnection("default",dbDriver,dbConnectionString,dbUser,dbPassword); } public SQLProxyServer() { this(defaultPort); } public SQLProxyServer(int port) { connections=new HashMap<String,T4<String,String,String,String>>(); credentials="test:aaa"; this.port=port; } /** * Credentials should be "username:password". */ public void setCredentials(String credentials){ this.credentials=credentials; } public void addConnection(String key,String dbDriver,String dbConnectionString,String dbUser,String dbPassword){ if(dbDriver==null) dbDriver=guessDBDriver(dbConnectionString); connections.put(key,t4(dbDriver,dbConnectionString,dbUser,dbPassword)); } public static String guessDBDriver(String dbConnectionString){ if(dbConnectionString.startsWith("jdbc:mysql:")) return "com.mysql.jdbc.Driver"; else if(dbConnectionString.startsWith("jdbc:microsoft:sqlserver:")) return "com.microsoft.jdbc.sqlserver.SQLServerDriver"; else if(dbConnectionString.startsWith("jdbc:hsqldb:")) return "org.hsqldb.jdbcDriver"; else return null; } public void setPort(int port){ this.port=port; } public int getPort(){return port;} public void setVerbose(boolean b){verbose=b;} public void setEcho(boolean b){echo=b;} public static void printUsage(){ System.out.println("Usage: java com.gripstudios.utils.sqlproxy.SQLProxyServer [driver] connectionString user password"); } public static void main(String[] args){ SQLProxyServer server=null; if(args.length>4) server=new SQLProxyServer(args[0],args[1],args[2],args[3],Integer.parseInt(args[4])); else if(args.length>3) server=new SQLProxyServer(args[0],args[1],args[2],args[3]); else if(args.length>2) server=new SQLProxyServer(args[0],args[1],args[2]); else { printUsage(); return; }; server.setVerbose(true); // server.setEcho(true); server.start(); try{ server.join(); }catch(InterruptedException ie){ ie.printStackTrace(); return; } } public Connection createConnection(String key){ T4<String,String,String,String> params=connections.get(key); if(params==null) return null; String dbDriver=params.e1; String dbConnectionString=params.e2; String dbUser=params.e3; String dbPassword=params.e4; try{ if(dbDriver!=null) Class.forName(dbDriver); Connection con=DriverManager.getConnection(dbConnectionString,dbUser,dbPassword); return con; } catch(Exception e){ System.out.println("Database connection failed with"); System.out.println("Driver: " + dbDriver); System.out.println("Connection string: " + dbConnectionString); System.out.println("User: " + dbUser); System.out.println("Password: " + dbPassword); e.printStackTrace(); return null; } } public void run() { running=true; if(verbose) System.out.println("Listening to port "+port); try{ ServerSocket ss; if(!useSSL){ ss=new ServerSocket(port); } else{ ss=SSLServerSocketFactory.getDefault().createServerSocket(port); } while(running){ try{ final Socket s=ss.accept(); if(verbose) System.out.println("Accepted connection from "+s.getRemoteSocketAddress().toString()); ServerThread t=new ServerThread(s); t.start(); }catch(Exception e){ if(printExceptions) e.printStackTrace(); } } }catch(Exception e){ if(printExceptions) e.printStackTrace(); } } public static final String RES_RESULTSET="0"; // query result is a result set public static final String RES_COUNT="1"; // query result is an update count public static final String RES_OK="2"; // command succesfull, no return value public static final String RES_ERROR="3"; // invalid command public static final String RES_AUTHREQUIRED="4"; // command requires authentication or invalid credentials when authenticating public static final String RES_CONREQUIRED="5"; // command requires an open database connection or invaling connection key when opening connection private class ServerThread extends Thread { private Connection connection; private Statement stmt; private Socket socket; private boolean running=true; private boolean sendExceptions=false; private Reader inReader; private Writer outWriter; private OutputStream out; private String lf="\r\n"; private String charset="UTF-8"; private boolean compress=false; private boolean authenticated=false; public ServerThread(Socket s) throws IOException,SQLException { socket=s; InputStream inStream=socket.getInputStream(); out=socket.getOutputStream(); if(echo) inStream=new EchoInputStream(inStream,out); inReader=new InputStreamReader(inStream,charset); outWriter=new OutputStreamWriter(out,charset); } public boolean openConnection(String key) throws SQLException { connection=createConnection(key); if(connection==null) return false; stmt=connection.createStatement(); return true; } public String readQuery() throws IOException { int c=-1; boolean escape=false; StringBuffer buf=new StringBuffer(); while( (c=inReader.read())!=-1 ){ if(!escape && c=='\\') escape=true; else { if(!escape && c=='\n') break; if(!escape && c=='\r') continue; if(!escape && c==8){ // backspace if(buf.length()>0) buf.deleteCharAt(buf.length()-1); } else buf.append((char)c); escape=false; } } return buf.toString(); } public void writeString(String s) throws IOException { if(s==null) outWriter.write("null"); else{ s=s.replace("\\","\\\\"); s=s.replace("\"","\\\""); outWriter.write("\""+s+"\""); } } public boolean isTypeNumeric(int type){ switch(type){ case Types.BIGINT: case Types.BOOLEAN: case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.INTEGER: case Types.NUMERIC: case Types.REAL: case Types.SMALLINT: case Types.TINYINT: return true; default: return false; } } public void handleException(Throwable e) throws IOException { e.printStackTrace(); outWriter.flush(); PrintWriter writer=new PrintWriter(outWriter); if(sendExceptions) e.printStackTrace(writer); writer.flush(); } public void sendResponse(String response) throws IOException { if(compress){ out=new GZIPOutputStream(socket.getOutputStream()); outWriter=new OutputStreamWriter(out); } outWriter.write(response); outWriter.flush(); if(compress) ((GZIPOutputStream)out).finish(); } public void run(){ if(credentials==null) authenticated=true; while(running){ try{ try{ String query=readQuery().trim(); if(query.equals("quit")) break; else if(query.equals("echo")){ InputStream inStream=socket.getInputStream(); out=socket.getOutputStream(); inStream=new EchoInputStream(inStream,out); inReader=new InputStreamReader(inStream,charset); } else if(query.equals("noecho")){ InputStream inStream=socket.getInputStream(); inReader=new InputStreamReader(inStream,charset); } else if(query.equals("exceptions")){ sendExceptions=true; } else if(query.equals("noexceptions")){ sendExceptions=false; } else if(query.equals("human")){ InputStream inStream=socket.getInputStream(); out=socket.getOutputStream(); inStream=new EchoInputStream(inStream,out); inReader=new InputStreamReader(inStream,charset); sendExceptions=true; } else if(query.equals("compress")){ compress=true; } else if(query.startsWith("login")){ if(authenticated){ sendResponse(RES_OK+lf); } else{ int ind=query.indexOf(" "); if(ind>0){ String parsed=query.substring(ind+1).trim(); if(parsed.equals(credentials)) { authenticated=true; sendResponse(RES_OK+lf); } else sendResponse(RES_AUTHREQUIRED+lf); } else sendResponse(RES_ERROR+lf); } } else if(authenticated) { if(query.startsWith("open")){ int ind=query.indexOf(" "); if(ind>0){ String parsed=query.substring(ind+1).trim(); if(openConnection(parsed)) sendResponse(RES_OK+lf); else sendResponse(RES_CONREQUIRED+lf); } else sendResponse(RES_ERROR+lf); } else if(connection==null){ sendResponse(RES_CONREQUIRED+lf); continue; } else if(stmt.execute(query)){ if(compress){ out=new GZIPOutputStream(socket.getOutputStream()); outWriter=new OutputStreamWriter(out,charset); } outWriter.write(RES_RESULTSET+lf); ResultSet rs=stmt.getResultSet(); ResultSetMetaData rsmd=rs.getMetaData(); StringBuffer metaData=new StringBuffer(); int columnCount=rsmd.getColumnCount(); int[] types=new int[columnCount]; for(int i=0;i<columnCount;i++){ if(i>0) metaData.append(","); String name=rsmd.getColumnName(i+1); int type=rsmd.getColumnType(i+1); types[i]=type; name=name.replace(",","\\,"); metaData.append(name+","+type); } outWriter.write(metaData.toString()+lf); while(rs.next()){ for(int i=0;i<columnCount;i++){ if(i>0) outWriter.write(","); if(isTypeNumeric(types[i])) outWriter.write(""+rs.getString(i+1)); else writeString(rs.getString(i+1)); } outWriter.write(lf); } outWriter.write(lf); outWriter.flush(); if(compress) ((GZIPOutputStream)out).finish(); rs.close(); } else{ int count=stmt.getUpdateCount(); sendResponse(RES_COUNT+lf+count+lf); } } else{ sendResponse(RES_AUTHREQUIRED+lf); } } catch(SQLException sqle){ if(compress){ out=new GZIPOutputStream(socket.getOutputStream()); outWriter=new OutputStreamWriter(out); } outWriter.write(RES_ERROR+lf); handleException(sqle); if(compress) ((GZIPOutputStream)out).finish(); } } catch(IOException ioe){ if(!ioe.getMessage().equals("Connection reset")){ ioe.printStackTrace(); } running=false; } } if(verbose) System.out.println("Closing connection from "+socket.getRemoteSocketAddress().toString()); dispose(); } public void dispose(){ try{ socket.close(); } catch(IOException ioe){ ioe.printStackTrace(); } try{ if(stmt!=null) stmt.close(); if(connection!=null) connection.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } } public static class EchoInputStream extends InputStream { private InputStream in; private OutputStream out; public EchoInputStream(InputStream in,OutputStream out){ this.in=in; this.out=out; } public int available() throws IOException {return in.available();} public void close() throws IOException {in.close();} public void mark(int readlimit){in.mark(readlimit);} public boolean markSupported(){return in.markSupported();} public int read() throws IOException { int r=in.read(); out.write(r); return r; } public int read(byte[] b) throws IOException { int r=in.read(b); out.write(b,0,r); return r; } public int read(byte[] b, int off, int len) throws IOException { int r=in.read(b,off,len); out.write(b,off,r); return r; } public void reset() throws IOException {in.reset();} public long skip(long n) throws IOException {return in.skip(n);} } }
19,815
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VirtualFileSystem.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/fileserver/VirtualFileSystem.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * VirtualFileSystem.java * * Created on 24.7.2006, 16:34 * */ package org.wandora.utils.fileserver; import java.io.File; /** * * A virtual file system is like a file system with directories which contain * other directories and files. Usually it is somehow mapped to a real file * system but with restrictions so that only certain files can be accessed * through it for security reasons. A simple way to do this is to mount * one directory as the root directory and then using everything inside that * as the file system. * * @author olli */ public interface VirtualFileSystem { /** * Returns an URL that can be used to access the given virtual file. * If the file system does not support this kind of operation, returns null. */ public String getURLFor(String file); /** * Gets the real File for a virtual file name. */ public File getRealFileFor(String file); /** * Lists all virtual directories inside the given virtual directory. */ public String[] listDirectories(String dir); /** * Lists all virtual files in the given virual directory. */ public String[] listFiles(String dir); }
1,997
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleFileServerClient.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/fileserver/SimpleFileServerClient.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SimpleFileServerClient.java * * Created on 25.7.2006, 12:27 * */ package org.wandora.utils.fileserver; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.net.Socket; import javax.net.ssl.SSLSocketFactory; /** * * You can use a SimpleFileServer with this class. Make a new instance of this * class, then use connect method to get a socket and connect to a file server. * After that you can use methods to upload files. * * Note: not all file server methods are currently implemented. * * @author olli */ public class SimpleFileServerClient { private String serverResponse=null; /** Creates a new instance of SimpleFileServerClient */ public SimpleFileServerClient() { } public String getLastServerResponse(){return serverResponse;} public Socket connect(String host,int port,boolean useSSL) throws IOException { Socket s=null; if(!useSSL){ s=new Socket(host,port); } else{ s=SSLSocketFactory.getDefault().createSocket(host,port); } return s; } public String readLine(InputStream in) throws IOException { return SimpleFileServer.readLine(in); } public boolean login(InputStream in,Writer out,String user,String pass) throws IOException { if(user!=null) out.write("login "+user+":"+pass+"\n"); else out.write("login\n"); out.flush(); serverResponse=readLine(in); if(serverResponse.startsWith("OK")) return true; else return false; } public void logout(Writer out) throws IOException { out.write("logout\n"); out.flush(); } public boolean sendFile(InputStream in,Writer out,OutputStream outStream,String filename,File f) throws IOException { return sendFile(in,out,outStream,filename,f.length(),new FileInputStream(f)); } public boolean sendFile(InputStream in,Writer out,OutputStream outStream,String filename,InputStream f) throws IOException { byte[] buf=new byte[32768]; int pos=0; int read=0; while( (read=f.read(buf,pos,buf.length-pos))!=-1 ){ pos+=read; if(pos==buf.length){ byte[] newbuf=new byte[buf.length*2]; System.arraycopy(buf,0,newbuf,0,buf.length); buf=newbuf; } } return sendFile(in,out,outStream,filename,pos,new ByteArrayInputStream(buf,0,pos)); } public boolean sendFile(InputStream in,Writer out,OutputStream outStream,String filename,long length,InputStream f) throws IOException { out.write("put "+filename+" "+length+"\n"); out.flush(); serverResponse=readLine(in); if(!serverResponse.startsWith("OK")) return false; byte[] buf=new byte[4096]; int read=0; while( (read=f.read(buf))!=-1 ){ outStream.write(buf,0,read); } outStream.flush(); serverResponse=readLine(in); if(!serverResponse.startsWith("OK")) return false; else return true; } public String getURLFor(InputStream in,Writer out,String file) throws IOException { out.write("geturlfor "+file+"\n"); out.flush(); serverResponse=readLine(in); if(!serverResponse.startsWith("OK")) return null; String res=readLine(in); if(res.equals("null")) return ""; else return res; } public static int FILE_EXISTS=0; public static int FILE_NOTEXISTS=1; public static int INVALIDFILE=2; public int fileExists(InputStream in,Writer out,String file) throws IOException { out.write("fileexists "+file+"\n"); out.flush(); serverResponse=readLine(in); if(!serverResponse.startsWith("OK")) return INVALIDFILE; String res=readLine(in); if(res.equalsIgnoreCase("true")) return FILE_EXISTS; else return FILE_NOTEXISTS; } }
4,941
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleVirtualFileSystem.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/fileserver/SimpleVirtualFileSystem.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SimpleVirtualFileSystem.java * * Created on 24.7.2006, 16:35 */ package org.wandora.utils.fileserver; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * * This is an implementation of VirtualFileSystem. It must be initialized with * a set of mount points. At least one for root directory and any number for other * directories. Nested directories are not supported (directories inside directories), * only subdirectories at root level. All files in the mounted directories show as * virtual files but directories in them are not visible or accessible (unless * separately mounted as virtual directories). * * @author olli */ public class SimpleVirtualFileSystem implements VirtualFileSystem/*,XMLParamAware*/ { private HashMap directories; private HashMap urls; /** Creates a new instance of SimpleVirtualFileSystem */ public SimpleVirtualFileSystem(String dir,String loc,String url) { this(); addDirectory(dir,loc,url); } public SimpleVirtualFileSystem() { directories=new HashMap(); urls=new HashMap(); } public String cleanFileName(String f){ f=f.replaceAll("[ \\\\/\\\"\\\'+&]","_"); return f; } public java.io.File getRealFileFor(String file) { int ind=file.indexOf("/"); if(ind==0) { if(file.length()>1) file=file.substring(1); else file=""; ind=file.indexOf("/"); } if(file.startsWith("..")) return null; String dir="/"; if(ind>0){ dir=file.substring(0,ind).trim(); } String f=file.substring(ind+1); if(f.indexOf("/")!=-1) return null; String real=(String)directories.get(dir); if(real==null) return null; real+=cleanFileName(f); return new File(real); } public String getURLFor(String file) { int ind=file.indexOf("/"); String dir="/"; if(ind>0){ dir=file.substring(0,ind).trim(); } String f=file.substring(ind+1); if(f.indexOf("/")!=-1) return null; String url=(String)urls.get(dir); if(url==null) return null; url+=cleanFileName(f); return url; } public String[] listDirectories(String dir) { if(dir.equals("/")){ ArrayList v=new ArrayList(); Iterator iter=directories.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); String d=(String)e.getKey(); if(!d.equals("/")){ v.add(d); } } return (String[])v.toArray(new String[0]); } else return new String[0]; } public String[] listFiles(String dir) { File f=getRealFileFor(dir); if(f==null || !f.isDirectory()) return null; File[] files=f.listFiles(); ArrayList v=new ArrayList(); for(int i=0;i<files.length;i++){ if(!files[i].isDirectory()){ v.add(files[i].getName()); } } return (String[])v.toArray(new String[0]); } public void addDirectory(String dir,String loc,String url){ directories.put(dir,loc); if(url!=null) urls.put(dir,url); } /* public void xmlParamInitialize(Element element, XMLParamProcessor processor) { NodeList nl=element.getElementsByTagName("directory"); for(int i=0;i<nl.getLength();i++){ Element e=(Element)nl.item(i); String dir=e.getAttribute("dir"); String loc=e.getAttribute("loc"); String url=e.getAttribute("url"); addDirectory(dir,loc,url); } } */ }
4,657
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleFileServer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/fileserver/SimpleFileServer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * SimpleFileServer.java * * Created on 24.7.2006, 16:33 * */ package org.wandora.utils.fileserver; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import javax.net.ssl.SSLServerSocketFactory; /** * For the ssl to work you need to create a certificate in command prompt with the * keytool utility (should be in jdk bin directory). * * For example: * keytool -genkey -keystore storefile -keyalg RSA * * After you have generated the certificate you need to run java with the following * parameters (or you may set the properties programmatically with System.setProperty): * -Djavax.net.ssl.keyStore=storefile -Djavax.net.ssl.keyStorePassword=password * * @author olli */ /* Initialize with XMLParamProcessor like this <fileserver xp:class="org.wandora.piccolo.services.FileServerService" xp:id="fileserver"> <param>8898</param> <param xp:class="com.gripstudios.utils.fileserver.SimpleVirtualFileSystem"> <param>/</param> <param>C:/</param> <param>http://localhost/</param> </param> <param>false</param> <param>user:password</param> </fileserver> <fileserver xp:idref="fileserver" xp:method="start"/> */ public class SimpleFileServer extends Thread { private int port; private boolean running; private boolean printExceptions; private boolean useSSL; private String requiredCredentials; private VirtualFileSystem fileSystem; private String lf="\r\n"; /** Creates a new instance of SimpleFileServer */ public SimpleFileServer(int port,VirtualFileSystem fileSystem) { this(port,fileSystem,false,null); } public SimpleFileServer(String port,VirtualFileSystem fileSystem,String useSSL,String credentials) { this(Integer.parseInt(port),fileSystem,Boolean.parseBoolean(useSSL),credentials); } public SimpleFileServer(int port,VirtualFileSystem fileSystem,boolean useSSL,String credentials) { this.port=port; this.fileSystem=fileSystem; this.useSSL=useSSL; this.requiredCredentials=credentials; } public void setRequiredCredentials(String credentials){ requiredCredentials=credentials; } public void setUseSSL(boolean value){ useSSL=value; } public static void main(String[] args) throws Exception { String user="admin"; String password="n1mda"; String mountPoint="."; String httpServer="http://localhost/"; int port=8898; for(int i=0;i<args.length;i++){ if(args[i].equals("-P")){ port=Integer.parseInt(args[i+1]); i++; } else if(args[i].equals("-u")){ user=args[i+1]; i++; } else if(args[i].equals("-p")){ password=args[i+1]; i++; } else if(args[i].equals("-m")){ mountPoint=args[i+1]; i++; } else if(args[i].equals("-s")){ httpServer=args[i+1]; i++; } } mountPoint=mountPoint.replace("\\","/"); if(!mountPoint.endsWith("/")) mountPoint+="/"; /* SimpleVirtualFileSystem fs=new SimpleVirtualFileSystem(); fs.addDirectory("/",mountPoint,httpServer); SimpleFileServer sfs=new SimpleFileServer(port,fs); sfs.setRequiredCredentials(user+":"+password); sfs.start();*/ SimpleFileServer sfs=new SimpleFileServer(port,new SimpleVirtualFileSystem("/",mountPoint,httpServer),false,user+":"+password); sfs.start(); System.out.println("Server running at port "+port); } @Override public void start(){ running=true; super.start(); } public void stopServer(){ running=false; this.interrupt(); } @Override public void run(){ try{ ServerSocket ss; if(!useSSL){ ss=new ServerSocket(port); } else{ ss=SSLServerSocketFactory.getDefault().createServerSocket(port); } while(running){ try{ final Socket s=ss.accept(); Thread t=new ClientThread(s); t.start(); }catch(Exception e){ if(printExceptions) e.printStackTrace(); } } }catch(Exception e){ if(printExceptions) e.printStackTrace(); } } public static String readLine(InputStream in) throws IOException { StringBuilder buf=new StringBuilder(); int c=0; while(true){ c=in.read(); if(c==-1) break; if( (char)c == '\r' ) continue; if( (char)c == '\n' ) break; buf.append((char)c); if(buf.length()>8192){ throw new IOException("Line buffer exeeded"); } } if(c==-1 && buf.length()==0) return null; return buf.toString(); } public static String[] parseLine(InputStream in) throws IOException { String line=readLine(in); if(line==null) return null; ArrayList<String> parsed=new ArrayList<String>(); StringBuffer item=new StringBuffer(); int pos=0; boolean escape=false; while(pos<line.length()){ char c=line.charAt(pos++); if(c=='\\') escape=true; else if(escape==true || c!=' ') { item.append(c); escape=false; } else{ parsed.add(item.toString()); item=new StringBuffer(); } } if(item.length()>0) parsed.add(item.toString()); return parsed.toArray(new String[parsed.size()]); } private class ClientThread extends Thread { private Socket socket; public ClientThread(Socket socket){ this.socket=socket; } @Override public void run(){ boolean loggedin=false; int logintries=0; try{ OutputStream outStream=socket.getOutputStream(); Writer out=new OutputStreamWriter(outStream); InputStream in=socket.getInputStream(); String[] parsed=parseLine(in); while(parsed!=null){ if(parsed.length>0){ if(!loggedin){ if(parsed[0].equals("login")){ if(requiredCredentials==null || (parsed.length>=2 && requiredCredentials.equals(parsed[1])) ){ loggedin=true; out.write("OK login ok"+lf); out.flush(); } else { logintries++; if(logintries>=3) try{ Thread.sleep(5000); } catch(InterruptedException ie){} out.write("ERR invalid user name or password"+lf); out.flush(); } } else if(parsed[0].equals("logout")){ out.write("OK terminating connection"+lf); out.flush(); break; } else{ out.write("ERR invalid command"+lf); out.flush(); } } else{ if(parsed[0].equals("listfiles")){ if(parsed.length>=2){ String[] files=fileSystem.listFiles(parsed[1]); out.write("OK sending file list"+lf); out.write(files.length+lf); for(int i=0;i<files.length;i++){ out.write(files[i]+lf); } out.flush(); } else { out.write("ERR directory not given"+lf); out.flush(); } } else if(parsed[0].equals("listdirs")){ if(parsed.length>=2){ String[] files=fileSystem.listDirectories(parsed[1]); out.write("OK sending dir list"+lf); out.write(files.length+lf); for(int i=0;i<files.length;i++){ out.write(files[i]+lf); } out.flush(); } else { out.write("ERR directory not given"+lf); out.flush(); } } else if(parsed[0].equals("fileexists")){ if(parsed.length>=2){ File f=fileSystem.getRealFileFor(parsed[1]); if(f!=null){ out.write("OK"+lf); out.write(""+f.exists()+lf); out.flush(); } else{ out.write("ERR invalid filename"+lf); out.flush(); } } else{ out.write("ERR file not given"+lf); out.flush(); } } else if(parsed[0].equals("get")){ if(parsed.length>=2){ File f=fileSystem.getRealFileFor(parsed[1]); if(!f.exists()){ out.write("ERR file does not exist"); out.flush(); } else{ long size=f.length(); out.write("OK sending file"+lf); out.write(size+lf); out.flush(); byte[] buf=new byte[4096]; try{ InputStream fin=new FileInputStream(f); int read=0; while( (read=fin.read(buf))!=-1 ){ outStream.write(buf,0,read); } } catch(IOException ioe){ ioe.printStackTrace(); break; } } } else{ out.write("ERR file not given"+lf); out.flush(); } } else if(parsed[0].equals("put")){ if(parsed.length>=3){ File f=fileSystem.getRealFileFor(parsed[1]); if(f==null){ out.write("ERR invalid file name"+lf); out.flush(); } else{ out.write("OK ready to receive file"+lf); out.flush(); long size=Long.parseLong(parsed[2]); OutputStream fout=new FileOutputStream(f); byte[] buf=new byte[4096]; long read=0; int bread=0; while(read<size){ if(size-read>buf.length) bread=in.read(buf); else bread=in.read(buf,0,(int)(size-read)); read+=bread; fout.write(buf,0,bread); } fout.close(); out.write("OK file received"+lf); out.flush(); } } else{ out.write("ERR file and/or size not given"+lf); out.flush(); } } else if(parsed[0].equals("geturlfor")){ if(parsed.length>=2){ String url=fileSystem.getURLFor(parsed[1]); out.write("OK"+lf); if(url==null) out.write("null"+lf); else out.write(url+lf); out.flush(); } else{ out.write("ERR file not given"+lf); out.flush(); } } else if(parsed[0].equals("logout")){ out.write("OK terminating connection"+lf); out.flush(); break; } else{ out.write("ERR invalid command"+lf); out.flush(); } } } parsed=parseLine(in); } }catch(Exception e){ if(printExceptions) e.printStackTrace(); } finally{ try{ socket.close(); }catch(IOException ioe){ ioe.printStackTrace(); } } } } }
16,839
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JavaScriptEncoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/JavaScriptEncoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * JavaScriptEncoder.java * * Created on July 28, 2004, 12:38 PM */ package org.wandora.utils.velocity; /** * * @author olli */ public class JavaScriptEncoder { /** Creates a new instance of JavaScriptEncoder */ public JavaScriptEncoder() { } public String encode(String s){ /* s=s.replaceAll("\\\\", "\\\\"); s=s.replaceAll("\"", "\\\""); s=s.replaceAll("\'", "\\\'");*/ return s; } }
1,263
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
HTMLEncoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/HTMLEncoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * HTMLEncoder.java * * Created on 19.7.2005, 14:04 */ package org.wandora.utils.velocity; /** * * @author olli */ public class HTMLEncoder { /** Creates a new instance of HTMLEncoder */ public HTMLEncoder() { } public String encode(String s){ s=s.replaceAll("&","&amp;"); s=s.replaceAll("<","&lt;"); return s; } }
1,184
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
URLEncoder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/URLEncoder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * URLEncoder.java * * Created on July 9, 2004, 2:55 PM */ package org.wandora.utils.velocity; /** * * @author olli */ public class URLEncoder { private String encoding; /** Creates a new instance of URLEncoder */ public URLEncoder() { this("UTF-8"); } public URLEncoder(String encoding) { this.encoding=encoding; } public String encode(String s){ try{ return java.net.URLEncoder.encode(s,encoding); }catch(Exception e){ return s; } } }
1,364
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VelocityMediaHelper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/VelocityMediaHelper.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * AssemblyHelper.java * * Created on July 14, 2004, 12:36 PM */ package org.wandora.utils.velocity; import java.nio.charset.StandardCharsets; import java.util.Iterator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class VelocityMediaHelper { /** Creates a new instance of VelocityMediaHelper */ public VelocityMediaHelper() { } public static String getTopicVideoThumbnail(Topic t) throws TopicMapException { Topic vwork=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/videowork"); Topic occ=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/videooccurrence"); Topic mocc=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/mediaoccurrence"); Topic tn=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/thumbnail"); Iterator<Association> iter=t.getAssociations(occ,vwork).iterator(); String found=null; while(iter.hasNext()){ Association a=iter.next(); Topic image=a.getPlayer(occ); if(image==null) continue; Iterator<Association> iter2=image.getAssociations(tn,mocc).iterator(); while(iter2.hasNext()){ Association a2=iter2.next(); Topic tnimage=a2.getPlayer(tn); if(tnimage==null) continue; if(tnimage.getSubjectLocator()!=null) { return tnimage.getSubjectLocator().toExternalForm(); } } } return found; } public static String getOccurrenceVideoThumbnail(Topic t) throws TopicMapException { Topic mocc=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/mediaoccurrence"); Topic tn=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/thumbnail"); Iterator<Association> iter2=t.getAssociations(tn,mocc).iterator(); while(iter2.hasNext()){ Association a2=iter2.next(); Topic tnimage=a2.getPlayer(tn); if(tnimage==null) continue; if(tnimage.getSubjectLocator()!=null) { return tnimage.getSubjectLocator().toExternalForm(); } } return null; } public static String getVideoPreview(Topic t){ return null; /* Topic occ=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/videooccurrence"); Topic preview=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/videopreview"); Iterator iter=t.getAssociations(preview,occ).iterator(); String found=null; while(iter.hasNext()){ Association a=(Association)iter.next(); Topic tnimage=a.getPlayer(preview); if(tnimage==null) continue; if(tnimage.getSubjectLocator()!=null) return tnimage.getSubjectLocator().toExternalForm(); } return found; */ } /* public static String getTopicImageThumbnail(Topic t){ Topic occ=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/imageoccurrence"); Topic tn=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/thumbnail"); Iterator iter=t.getAssociations().iterator(); while(iter.hasNext()) { try { Association a=(Association)iter.next(); Topic image=a.getPlayer(occ); if(image != null) return image.getSubjectLocator().toExternalForm(); } catch (Exception e) { e.printStackTrace(); } } return null; }*/ public static String getTopicImageThumbnail(Topic t) throws TopicMapException { Topic vwork=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/visualwork"); Topic occ=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/imageoccurrence"); Topic mocc=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/mediaoccurrence"); Topic tn=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/thumbnail"); Iterator<Association> iter=t.getAssociations(occ,vwork).iterator(); String found=null; while(iter.hasNext()){ Association a=iter.next(); Topic image=a.getPlayer(occ); if(image==null) continue; Iterator<Association> iter2=image.getAssociations(tn,mocc).iterator(); while(iter2.hasNext()){ Association a2=iter2.next(); Topic tnimage=a2.getPlayer(tn); if(tnimage==null) continue; if(tnimage.getSubjectLocator()!=null) { return tnimage.getSubjectLocator().toExternalForm(); } } if(found==null && image.getSubjectLocator()!=null) { found=image.getSubjectLocator().toExternalForm(); } } return found; } public static String getTopicTVImage(Topic t) throws TopicMapException { Topic vwork=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/visualwork"); Topic occ=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/imageoccurrence"); Topic mocc=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/mediaoccurrence"); Topic tn=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/tvimage"); Iterator<Association> iter=t.getAssociations(occ,vwork).iterator(); String found=null; while(iter.hasNext()){ Association a=iter.next(); Topic image=a.getPlayer(occ); if(image==null) continue; Iterator<Association> iter2=image.getAssociations(tn,mocc).iterator(); while(iter2.hasNext()){ Association a2=iter2.next(); Topic tnimage=a2.getPlayer(tn); if(tnimage==null) continue; if(tnimage.getSubjectLocator()!=null) { return tnimage.getSubjectLocator().toExternalForm(); } } if(found==null && image.getSubjectLocator()!=null) { found=image.getSubjectLocator().toExternalForm(); } } return found; } public static String getTopicImage(Topic t) throws TopicMapException { Topic vwork=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/visualwork"); Topic occ=t.getTopicMap().getTopic("http://www.gripstudios.com/wandora/common/imageoccurrence"); Iterator<Association> iter=t.getAssociations(occ,vwork).iterator(); while(iter.hasNext()){ Association a=iter.next(); Topic image=a.getPlayer(occ); if(image==null) continue; if(image.getSubjectLocator()!=null) { return image.getSubjectLocator().toExternalForm(); } } return null; } public String trimNonAlphaNums(String word) { if(word == null || word.length() < 1) return ""; int i=0; int j=word.length()-1; for(; i<word.length() && !Character.isJavaIdentifierPart(word.charAt(i)); i++); for(; j>i+1 && !Character.isJavaIdentifierPart(word.charAt(j)); j--); return word.substring(i,j+1); } public String encodeURL(String s) { try { return java.net.URLEncoder.encode(s, StandardCharsets.UTF_8.name()); } catch(Exception e) { return s; } } public String populateLinks(String text, String linkTemplate) { if(text != null && text.length()>0) { String DELIMITERS = " \n\t',.\""; StringBuilder newText = new StringBuilder(""); String searchword; String link; String substring; int index=0; int wordStart; int wordEnd; while(index < text.length()) { while(index < text.length() && DELIMITERS.indexOf(text.charAt(index)) != -1) { newText.append(text.charAt(index)); index++; } // pass html/xml tags while(index < text.length() && text.charAt(index) == '<') { while(index < text.length() && text.charAt(index) != '>') { newText.append(text.charAt(index)); index++; } newText.append(text.charAt(index)); index++; } // potential word found wordStart=index; while(index < text.length() && DELIMITERS.indexOf(text.charAt(index)) == -1 && text.charAt(index) != '<') { index++; } if(index > wordStart) { substring = text.substring(wordStart, index); // try { substring = encodeHTML(substring); } catch (Exception e) {} if(index-wordStart > 3) { searchword = trimNonAlphaNums(substring); if(searchword.length() > 3) { link = linkTemplate.replaceAll("%searchw%", encodeURL(searchword)); link = link.replaceAll("%word%", substring); newText.append(link); } else { newText.append(substring); } } else { newText.append(substring); } } } text = newText.toString(); } return text; } public static class TreeNode { public Topic content; public boolean openChildren; public boolean closeChildren; public TreeNode(Topic content,boolean openChildren,boolean closeChildren){ this.content=content; this.openChildren=openChildren; this.closeChildren=closeChildren; } } }
11,294
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceMaker.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/InstanceMaker.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * InstanceMaker.java * * Created on July 12, 2004, 10:55 AM */ package org.wandora.utils.velocity; /** * Use this class in velocity when you need to make new instances of some class in * the template. * * @author olli */ public class InstanceMaker { private Class c; /** Creates a new instance of InstanceMaker */ public InstanceMaker(String cls) throws Exception { c=Class.forName(cls); } public Object make() throws Exception { return c.newInstance(); } }
1,337
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GenericVelocityHelper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/GenericVelocityHelper.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * GenericVelocityHelper.java * * Created on 17. joulukuuta 2004, 10:54 */ package org.wandora.utils.velocity; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.utils.IObox; import org.wandora.utils.Textbox; /** * * @author olli, akivela */ public class GenericVelocityHelper { /** Creates a new instance of GenericVelocityHelper */ public GenericVelocityHelper() { } public static Hashtable getBinaryAssociations(Topic topic) { return null; } public static Topic getFirstPlayerWithRole(Topic topic, String roleSI) { try { ArrayList<Topic> players = getPlayersWithRole(topic, roleSI); if(players.size() > 0) return players.get(0); } catch (Exception e) { e.printStackTrace(); } return null; } public static ArrayList<Topic> getPlayersWithRole(Topic topic, String roleSI) throws TopicMapException { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null && roleSI != null) { Topic role = topic.getTopicMap().getTopic(roleSI); if(role != null) { Collection<Association> associations = topic.getAssociations(); for(Association a : associations ) { try { if(a.getPlayer(role) != null) players.add(a.getPlayer(role)); } catch (Exception e) { e.printStackTrace(); } } } } return players; } public static ArrayList<Topic> getPlayersWithRole(Collection<Topic> topics, String roleSI) { ArrayList<Topic> players = new ArrayList<Topic>(); for(Topic topic : topics){ try { players.addAll(getPlayersWithRole(topic, roleSI)); } catch (Exception e) { e.printStackTrace(); } } return players; } public static ArrayList<Topic> getPlayersWithRoles(Topic topic, String[] roleSIs) { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null) { String roleSI = null; for(int i=0; i<roleSIs.length; i++) { try { roleSI = roleSIs[i]; players.addAll(getPlayersWithRole( topic, roleSI )); } catch (Exception e) { e.printStackTrace(); } } } return players; } public static ArrayList<Topic> getPlayersWithRoles(Topic topic, Collection<String> roleSIs) { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null) { for(String roleSI : roleSIs){ try { players.addAll(getPlayersWithRole( topic, roleSI )); } catch (Exception e) { e.printStackTrace(); } } } return players; } public static ArrayList<Topic> getPlayersWithRoles(Collection<Topic> topics, Collection<String> roleSIs) { ArrayList<Topic> players = new ArrayList<Topic>(); for(Topic topic : topics){ try { players.addAll(getPlayersWithRoles(topic, roleSIs)); } catch (Exception e) { e.printStackTrace(); } } return players; } public static ArrayList<Topic> getPlayersWithRoles(Collection<Topic> topics, String[] roleSIs) { ArrayList<Topic> players = new ArrayList<Topic>(); for(Topic topic : topics){ try { players.addAll(getPlayersWithRoles(topic, roleSIs)); } catch (Exception e) { e.printStackTrace(); } } return players; } public static ArrayList<Topic> getAllPlayers(Topic topic) throws TopicMapException { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null) { Collection<Association> associations = topic.getAssociations(); for(Association a : associations){ try { Collection<Topic> roles = a.getRoles(); for(Topic role : roles){ if(!a.getPlayer(role).mergesWithTopic(topic)) players.add(a.getPlayer(role)); } } catch (Exception e) { e.printStackTrace(); } } } return players; } public static ArrayList<Topic> getPlayers(Topic topic, String associationTypeSI) throws TopicMapException { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null && associationTypeSI != null) { Topic type = topic.getTopicMap().getTopic(associationTypeSI); if(type != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations ){ try { Collection<Topic> roles = a.getRoles(); for(Topic role : roles){ if(!a.getPlayer(role).mergesWithTopic(topic)) players.add(a.getPlayer(role)); } } catch (Exception e) { e.printStackTrace(); } } } } return players; } public static Topic getFirstPlayer(Topic topic, String associationTypeSI, String roleSI) { try { ArrayList<Topic> players = getPlayers(topic, associationTypeSI, roleSI); if(players.size() > 0) return players.get(0); } catch (Exception e) { e.printStackTrace(); } return null; } public static ArrayList<Topic> getPlayers(Topic topic, String associationTypeSI, String roleSI) throws TopicMapException { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null && associationTypeSI != null && roleSI != null) { Topic type = topic.getTopicMap().getTopic(associationTypeSI); Topic role = topic.getTopicMap().getTopic(roleSI); if(type != null && role != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations){ try { if(a.getPlayer(role) != null) players.add(a.getPlayer(role)); } catch (Exception e) { e.printStackTrace(); } } } } return players; } public static ArrayList<Topic> getPlayers(Topic topic, Topic type, Topic role) throws TopicMapException { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null && type != null && role != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations){ try { if(a.getPlayer(role) != null) players.add(a.getPlayer(role)); } catch (Exception e) { e.printStackTrace(); } } } return players; } public static ArrayList<Topic> getPlayers(Collection<Topic> topics, String associationTypeSI, String roleSI) { ArrayList<Topic> players = new ArrayList<Topic>(); for(Topic topic : topics){ try { players.addAll(getPlayers(topic, associationTypeSI, roleSI)); } catch (Exception e) { e.printStackTrace(); } } return players; } public static ArrayList<Topic> getPlayers(Topic topic, String associationTypeSI, String roleSI, String hasRole, String hasPlayer) throws TopicMapException { ArrayList<Topic> players = new ArrayList<Topic>(); if(topic != null && associationTypeSI != null && roleSI != null && hasRole != null && hasPlayer != null) { Topic type = topic.getTopicMap().getTopic(associationTypeSI); Topic role = topic.getTopicMap().getTopic(roleSI); Topic hasRoleTopic = topic.getTopicMap().getTopic(hasRole); Topic hasPlayerTopic = topic.getTopicMap().getTopic(hasPlayer); if(type != null && role != null && hasRoleTopic != null && hasPlayerTopic != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations){ try { Topic player=a.getPlayer(role); if(player != null) { Topic checkPlayer=a.getPlayer(hasRoleTopic); if(checkPlayer!=null && checkPlayer.mergesWithTopic(hasPlayerTopic)) { players.add(player); } } } catch (Exception e) { e.printStackTrace(); } } } } return players; } public static ArrayList<Topic> getPlayers(Collection<Topic> topics, String associationTypeSI, String roleSI, String hasRole, String hasPlayer) { ArrayList<Topic> players = new ArrayList<Topic>(); for(Topic topic : topics){ try { players.addAll(getPlayers(topic, associationTypeSI, roleSI, hasRole, hasPlayer)); } catch (Exception e) { e.printStackTrace(); } } return players; } public static ArrayList<Topic> getSortedPlayers(Topic topic, String associationTypeSI, String roleSI, String sortRole, String lang) throws TopicMapException { ArrayList<Topic[]> players = new ArrayList<>(); ArrayList<Topic> sortedPlayers = new ArrayList<Topic>(); if(topic != null && associationTypeSI != null && roleSI != null && sortRole != null) { Topic type = topic.getTopicMap().getTopic(associationTypeSI); Topic role = topic.getTopicMap().getTopic(roleSI); Topic sortRoleTopic = topic.getTopicMap().getTopic(sortRole); if(type != null && role != null && sortRole != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations) { try { Topic player = a.getPlayer(role); if(player != null) { Topic sortPlayer = a.getPlayer(sortRoleTopic); if(sortPlayer != null) { int i=0; while(i<players.size()) { Topic[] tc = (Topic[]) players.get(i); Topic anotherSortPlayer = tc[0]; if(anotherSortPlayer != null) { String sortName = sortPlayer.getSortName(lang); String anotherSortName = anotherSortPlayer.getSortName(lang); if(sortName != null && anotherSortName != null) { if(sortName.compareTo(anotherSortName) < 0) { break; } } } i++; } players.add(i, new Topic[] { sortPlayer, player } ); } else { players.add(0, new Topic[] { null, player } ); } } } catch (Exception e) { e.printStackTrace(); } } } } //System.out.println("players.size() == " + players.size()); for(int i=0; i<players.size(); i++) { Topic[] tc = (Topic[]) players.get(i); if(tc != null && tc.length == 2) { Topic player = tc[1]; if(player != null) { sortedPlayers.add(player); } } } //System.out.println("sortedPlayers.size() == " + sortedPlayers.size()); return sortedPlayers; } public static ArrayList<Topic> getSortedPlayers(Topic topic, Collection<String> associationTypesSI, Collection<String> rolesSI, String sortRole, String lang) throws TopicMapException { ArrayList<Topic[]> players = new ArrayList<>(); ArrayList<Topic> sortedPlayers = new ArrayList<Topic>(); Iterator<String> ai = associationTypesSI.iterator(); Iterator<String> ri = rolesSI.iterator(); while(ai.hasNext() && ri.hasNext()) { String associationTypeSI = ai.next(); String roleSI = ri.next(); if(topic != null && associationTypeSI != null && roleSI != null && sortRole != null) { Topic type = topic.getTopicMap().getTopic(associationTypeSI); Topic role = topic.getTopicMap().getTopic(roleSI); Topic sortRoleTopic = topic.getTopicMap().getTopic(sortRole); if(type != null && role != null && sortRole != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations ) { try { Topic player = a.getPlayer(role); if(player != null) { Topic sortPlayer = a.getPlayer(sortRoleTopic); if(sortPlayer != null) { int i=0; while(i<players.size()) { Topic[] tc = (Topic[]) players.get(i); Topic anotherSortPlayer = tc[0]; if(anotherSortPlayer != null) { String sortName = sortPlayer.getSortName(lang); String anotherSortName = anotherSortPlayer.getSortName(lang); if(sortName != null && anotherSortName != null) { if(sortName.compareTo(anotherSortName) < 0) { break; } } } i++; } players.add(i, new Topic[] { sortPlayer, player } ); } else { players.add(0, new Topic[] { null, player } ); } } } catch (Exception e) { e.printStackTrace(); } } } } } //System.out.println("players.size() == " + players.size()); for(int i=0; i<players.size(); i++) { Topic[] tc = (Topic[]) players.get(i); if(tc != null && tc.length == 2) { Topic player = tc[1]; if(player != null) { sortedPlayers.add(player); } } } //System.out.println("sortedPlayers.size() == " + sortedPlayers.size()); return sortedPlayers; } public static ArrayList<Topic> getTypesOfRequiredType(Topic topic, String requiredTypeSI) { ArrayList<Topic> selectedTypes = new ArrayList<Topic>(); if(topic != null && requiredTypeSI != null) { try { Collection<Topic> types = topic.getTypes(); Topic requiredType = topic.getTopicMap().getTopic(requiredTypeSI); if(requiredType != null) { for(Topic type : types) { if(type.getTypes().contains(requiredType)) { selectedTypes.add(type); } } } } catch (Exception e) { e.printStackTrace(); } } return selectedTypes; } public static ArrayList<String> getSLsOfPlayers(Topic topic, String associationTypeSI, String roleSI) throws TopicMapException { ArrayList<Topic> players = getPlayers(topic, associationTypeSI, roleSI); ArrayList<String> locators = new ArrayList<String>(); for(int i=0; i<players.size(); i++) { if(players.get(i) != null) { Locator sl = players.get(i).getSubjectLocator(); if(sl != null) { locators.add(sl.toExternalForm()); } } } return locators; } public static ArrayList<String> getSLsOfTopics(Collection<Topic> topics) { ArrayList<String> locators = new ArrayList<String>(); for(Topic topic : topics) { try { Locator sl = topic.getSubjectLocator(); if(sl != null) { locators.add(sl.toExternalForm()); } } catch (Exception e) { e.printStackTrace(); } } return locators; } public static String getFirstExistingURL(Collection<String> sls) { for(String sl : sls) { try { if(urlExists(sl)) return sl; } catch (Exception e) { e.printStackTrace(); } } return null; } public static Collection<String> replaceInStrings(Collection<String> ss, String regex, String replacement) { ArrayList<String> newss = new ArrayList<String>(); for(String s : ss) { try { newss.add(s.replaceAll(regex, replacement)); } catch (Exception e) { e.printStackTrace(); } } return newss; } public static Collection<String> addDirToStringPaths(Collection<String> ss, String dir) { ArrayList<String> newss = new ArrayList<String>(); for(String s : ss) { try { s = addDirToStringPath(s, dir); if(s != null) newss.add(s); } catch (Exception e) { e.printStackTrace(); } } return newss; } public static String addDirToStringPath(String s, String dir) { if(s != null && dir != null) { int i = s.lastIndexOf('/'); if(i>0) { s = s.substring(0, i) + "/" + dir + s.substring(i); } else { s = dir + "/" + s; } return s; } return null; } public static <K> ArrayList<K> crop(Collection<K> collection, int start, int end) { ArrayList<K> cropped = new ArrayList<>(); if(collection != null) { int s = collection.size(); Iterator<K> iterator = collection.iterator(); for(int i=0; i<s && i<start; i++) { iterator.next(); } for(int i=start; i<s && i<end; i++) { cropped.add(iterator.next()); } } return cropped; } public static <K> ArrayList<K> cropPage(Collection<K> collection, int page, int pageSize) { ArrayList<K> cropped = new ArrayList<K>(); if(collection != null) { int start = Math.max(0, (page-1)*pageSize); int end = page * pageSize; int s = collection.size(); Iterator<K> iterator = collection.iterator(); for(int i=0; i<start && i<s; i++) { iterator.next(); } for(int i=start; i<s && i<end; i++) { cropped.add(iterator.next()); } } return cropped; } public static <K> ArrayList<K> makeIntersection(Collection<? extends K> a, Collection<? extends K> b) { ArrayList<K> intersection = new ArrayList<K>(); if(a != null && b != null && b.size() > 0) { K o = null; for(Iterator<? extends K> iter = a.iterator(); iter.hasNext(); ) { o=iter.next(); if(b.contains(o)) intersection.add(o); } } return intersection; } public static <K> Collection<K> removeDuplicates(Collection<K> objects) { LinkedHashSet<K> newCollection = new LinkedHashSet<K>(); K object = null; newCollection.addAll(objects); // LinkedHashSet only allows each element once /* for(Iterator<K> i = objects.iterator(); i.hasNext(); ) { try { object = i.next(); if(!newCollection.contains(object)) newCollection.add(object); } catch (Exception e) { e.printStackTrace(); } }*/ return newCollection; } public static boolean contains(Collection objects, Object o) { if(objects == null || o == null) return false; else return objects.contains(o); } public static ArrayList<Topic> collectTopicsOfType(TopicMap topicmap, Topic typeTopic, int depth) { LinkedHashSet<Topic> results = new LinkedHashSet<Topic>(); ArrayList<Topic> temp = null; // new topics of previous iteration ArrayList<Topic> temp2 = new ArrayList<Topic>(); // new topics of current iteration ArrayList<Topic> temp3 = null; // candidates for new topics of current iteration results.add(typeTopic); temp2.add(typeTopic); for(int i=0; i<depth; i++) { temp=temp2; temp2=new ArrayList<Topic>(); temp3=new ArrayList<Topic>(); for(Topic t : temp) { try { temp3.addAll(topicmap.getTopicsOfType(t)); } catch (Exception e) { e.printStackTrace(); } } for(Topic t : temp3) { try { if(!results.contains(t)){ results.add(t); temp2.add(t); } } catch (Exception e) { e.printStackTrace(); } } } return new ArrayList<Topic>(results); } public static ArrayList<Topic> collectPlayers(TopicMap topicmap, Topic topic, String associationTypeSI, String roleSI, String hasRole, String hasPlayer, int depth) { LinkedHashSet<Topic> results = new LinkedHashSet<Topic>(); ArrayList<Topic> temp = null; // new topics of previous iteration ArrayList<Topic> temp2 = new ArrayList<Topic>(); // new topics of current iteration ArrayList<Topic> temp3 = null; // candidates for new topics of current iteration results.add(topic); temp2.add(topic); for(int i=0; i<depth; i++) { temp=temp2; temp2=new ArrayList<Topic>(); temp3 = new ArrayList<Topic>(); for(Topic t : temp) { try { temp3.addAll(getPlayers(t, associationTypeSI, roleSI, hasRole, hasPlayer)); } catch (Exception e) { e.printStackTrace(); } } for(Topic t : temp3) { try { if(!results.contains(t)) { results.add(t); temp2.add(t); } } catch (Exception e) { e.printStackTrace(); } } } return new ArrayList<Topic>(results); } public static <K> K extractRandomObject(Collection<K> c) { if(c == null || c.size() == 0) return null; int randomIndex = (int) (Math.random() * c.size()); Iterator<K> iter = c.iterator(); K o = iter.next(); while(iter.hasNext() && randomIndex-- > 0) o = iter.next(); return o; } public static <K> Vector<K> extractRandomVector(Collection<K> c, int newSize) { Vector<K> cropped = new Vector<>(); if( c == null || c.size() < 1 || newSize < 1) return cropped; int s = c.size(); int randomStep = 0; Iterator<K> iter = c.iterator(); for(int i=0; i<newSize; i++) { randomStep = (int) Math.floor(Math.random() * (s/newSize)) -1; while(iter.hasNext() && randomStep-- > 0) iter.next(); if(iter.hasNext()) cropped.add(iter.next()); } return cropped; } public static <K> List<K> extractRandomList(Collection<K> c, int newSize) { ArrayList<K> cropped = new ArrayList<>(); if( c == null || c.size() < 1 || newSize < 1) return cropped; int s = c.size(); int randomStep = 0; Iterator<K> iter = c.iterator(); for(int i=0; i<newSize; i++) { randomStep = (int) Math.floor(Math.random() * (s/newSize)) -1; while(iter.hasNext() && randomStep-- > 0) iter.next(); if(iter.hasNext()) cropped.add(iter.next()); } return cropped; } public static ArrayList<Topic> getRoles(Topic topic, String associationTypeSI) throws TopicMapException { ArrayList<Topic> roleList = new ArrayList<Topic>(); if(topic != null && associationTypeSI != null) { Topic type = topic.getTopicMap().getTopic(associationTypeSI); if(type != null) { Collection<Association> associations = topic.getAssociations(type); for(Association a : associations) { try { Collection<Topic> roles = a.getRoles(); for(Topic role : roles) { if(!roleList.contains(role)) roleList.add(role); } } catch (Exception e) { e.printStackTrace(); } } } } return roleList; } public static ArrayList<Association> getVisibleAssociations(Topic topic) throws TopicMapException { ArrayList<Association> associationVector = new ArrayList<Association>(); if(topic != null) { Collection<Association> associations = topic.getAssociations(); for(Association a : associations) { if(TMBox.associationVisible(a)) associationVector.add(a); } } return associationVector; } public static Collection<Association> removeAssociationsByType(Collection<Association> v, Topic type) throws TopicMapException { ArrayList<Association> ret= new ArrayList<Association>(); if(v != null && type != null) { for(Association a : v) { if(a!=null && !a.getType().equals(type)) { ret.add(a); } } } return ret; } public static Collection<Association> cropAssociationsByType(Topic topic, Collection v, String associationTypeSI) throws TopicMapException { if(associationTypeSI==null) return new ArrayList<Association>(); Topic type = topic.getTopicMap().getTopic(associationTypeSI); return cropAssociationsByType(v, type); } public static Collection<Association> cropAssociationsByType(Collection<Association> v, Topic type) throws TopicMapException { ArrayList<Association> ret = new ArrayList<Association>(); if(v != null && type != null) { for(Association a : v) { if(a!=null && a.getType().equals(type)) { ret.add(a); } } } return ret; } public static Collection<Topic> cropTopicsByVisibility(Collection<Topic> v) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); if(v != null && v.size() > 0) { for(Topic t : v){ if(t!=null && TMBox.topicVisible(t)) ret.add(t); } } return ret; } public static ArrayList<Association> cropAssociationsByVisibility(Collection<Association> v) { ArrayList<Association> ret = new ArrayList<Association>(); if(v != null) { for(Association a : v){ try{ if(a!=null && TMBox.associationVisible(a)) ret.add(a); }catch(Exception e){ e.printStackTrace(); } } } return ret; } public static Collection<Topic> cropTopicsByClass(Collection<Topic> v, Topic typeTopic) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); if(v != null && v.size() > 0 && typeTopic != null) { for(Topic t : v) { if(t!=null && t.isOfType(typeTopic)) ret.add(t); } } return ret; } public static Collection<Topic> removeTopicsByClass(Collection<Topic> v, Topic typeTopic) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); if(v != null && v.size() > 0 && typeTopic != null) { for(Topic t : v) { if(t!=null && !t.isOfType(typeTopic)) ret.add(t); } } return ret; } public static Collection<Topic> cropTopicsIfHasAssociations(Collection<Topic> v, Topic associationTypeTopic) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); Collection<Association> typedAssociations = null; if(v != null && v.size() > 0 && associationTypeTopic != null) { for(Topic t : v) { if(t==null) continue; typedAssociations = t.getAssociations(associationTypeTopic); if(typedAssociations != null && typedAssociations.size() > 0) ret.add(t); } } return ret; } public static Collection<Topic> cropTopicsIfHasPlayer(Collection<Topic> v, Topic associationTypeTopic, Topic role, Topic player) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); Topic aplayer = null; Collection<Association> typedAssociations = null; if(v != null && v.size() > 0 && associationTypeTopic != null && role != null && player != null) { for(Topic t : v) { if(t!=null && !t.isRemoved()) { typedAssociations = t.getAssociations(associationTypeTopic); if(typedAssociations != null && typedAssociations.size() > 0) { for(Association a : typedAssociations) { aplayer = a.getPlayer(role); if(aplayer != null && player.mergesWithTopic(aplayer)) { ret.add(t); } } } } } } return ret; } public static Collection<Topic> cropTopicsIfHasPlayerRegex(Collection<Topic> v, Topic associationTypeTopic, Topic role, String playerRegex) throws TopicMapException { // By default we just find the regex -- partial match is valid match! return cropTopicsIfHasPlayerRegex(v, associationTypeTopic, role, playerRegex, true); } public static Collection<Topic> cropTopicsIfHasPlayerRegex(Collection<Topic> v, Topic associationTypeTopic, Topic role, String playerRegex, boolean find) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); Topic aplayer = null; String aplayerBasename = null; Collection<Association> associations = null; Pattern playerPattern = null; Matcher playerMatcher = null; try { if( playerRegex != null ) { playerPattern = Pattern.compile(playerRegex); } } catch(Exception e) { e.printStackTrace(); } if(v != null && v.size() > 0 && associationTypeTopic != null && role != null && playerPattern != null) { for(Topic t : v) { associations = t.getAssociations(associationTypeTopic); if(associations != null && associations.size() > 0) { for(Association a : associations) { aplayer = a.getPlayer(role); if(aplayer != null) { aplayerBasename = aplayer.getBaseName(); if(aplayerBasename != null) { playerMatcher = playerPattern.matcher(aplayerBasename); if(find) { // Accept partial match! if(playerMatcher.find()) { ret.add(t); } } else { // accept only full matches! if(playerMatcher.matches()) { ret.add(t); } } } } } } } } return ret; } public static Collection<Topic> cropTopicsIfHasAssociationWithInPlayer(Collection<Topic> v, Topic associationTypeTopic, Topic role, Topic associationTypeTopic2) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); Topic player = null; Collection<Association> typedAssociations = null; Collection<Association> typedAssociations2 = null; if(v != null && v.size() > 0 && associationTypeTopic != null && role != null && associationTypeTopic2 != null) { for(Topic t : v) { if(t!=null){ typedAssociations = t.getAssociations(associationTypeTopic); if(typedAssociations != null && typedAssociations.size() > 0) { for(Association a : typedAssociations ) { if(a != null) { player = a.getPlayer(role); if(player != null) { typedAssociations2 = player.getAssociations(associationTypeTopic2); if(typedAssociations2 != null && typedAssociations2.size() > 0) { ret.add(t); break; } } } } } } } } return ret; } public static Collection<Topic> cropTopicsIfHasPlayerWithInPlayer(Collection<Topic> v, Topic associationTypeTopic, Topic role, Topic associationTypeTopic2, Topic role2, Topic player2) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); Topic player = null; Topic playerInPlayer = null; Collection<Association> typedAssociations = null; Collection<Association> typedAssociations2 = null; if(v != null && v.size() > 0 && associationTypeTopic != null && role != null && associationTypeTopic2 != null) { VLOOP: for(Topic t : v) { if(t!=null) { typedAssociations = t.getAssociations(associationTypeTopic); if(typedAssociations != null && typedAssociations.size() > 0) { for(Association a : typedAssociations) { if(a != null) { player = a.getPlayer(role); if(player != null) { typedAssociations2 = player.getAssociations(associationTypeTopic2); if(typedAssociations2 != null && typedAssociations2.size() > 0) { for(Association a3 : typedAssociations2) { playerInPlayer = a3.getPlayer(role2); if(playerInPlayer.mergesWithTopic(player2)) { ret.add(t); continue VLOOP; } } } } } } } } } } return ret; } public static Collection<Topic> cropTopicsByRegex(Collection<Topic> v, String lang, String regex, boolean strictMatch) throws TopicMapException { return cropTopicsByRegex(v, lang, regex, strictMatch, false); } public static Collection<Topic> cropTopicsByRegex(Collection<Topic> v, String lang, String regex, boolean strictMatch, boolean caseSensitive) throws TopicMapException { ArrayList<Topic> ret = new ArrayList<Topic>(); String topicName = null; if(v != null && v.size() > 0 && lang != null && regex != null && regex.length() > 0) { Pattern pattern = (caseSensitive ? Pattern.compile(regex) : Pattern.compile(regex, Pattern.CASE_INSENSITIVE)); for(Topic t : v) { try { if(t!=null) { if(t.isRemoved()) continue; topicName = t.getDisplayName(lang); if(topicName == null) topicName = t.getBaseName(); if(topicName == null) topicName = t.getOneSubjectIdentifier().toExternalForm(); if(strictMatch) { if( pattern.matcher(topicName).matches() ) { ret.add(t); } } else { if( pattern.matcher(topicName).find() ) { ret.add(t); } } } } catch(Exception e) { e.printStackTrace(); } } } return ret; } public static Hashtable<Topic, ArrayList<Topic>> groupTopicsByType(Collection<Topic> topics) { Hashtable<Topic, ArrayList<Topic>> groupedTopics = new Hashtable<Topic, ArrayList<Topic>>(); if(topics != null) { Collection<Topic> types = null; Iterator<Topic> typeIter = null; ArrayList<Topic> typeGroup = null; for(Topic t : topics) { try { types = t.getTypes(); for(Topic type : types) { if(type != null) { typeGroup = groupedTopics.get(type); if(typeGroup == null) { typeGroup = new ArrayList<Topic>(); groupedTopics.put(type, typeGroup); } typeGroup.add(t); } } } catch(Exception e) { e.printStackTrace(); } } } return groupedTopics; } public static Collection<Topic> basenamePrefixSearch(TopicMap topicmap, String lang, String prefix, Topic typeTopic) { try { if(typeTopic != null && topicmap != null && lang != null && prefix != null) { ArrayList<Topic> searchResults = new ArrayList<Topic>(); Collection<Topic> topics = topicmap.getTopicsOfType(typeTopic); Topic t = null; String bn = null; for(Iterator<Topic> iter=topics.iterator(); iter.hasNext(); ) { t = iter.next(); bn = t.getBaseName(); if(bn != null && bn.startsWith(prefix)) searchResults.add(t); } return searchResults; } } catch(Exception e) { e.printStackTrace(); } return new ArrayList<Topic>(); } public static Collection<Topic> searchTopics(TopicMap topicmap, String lang, String query) { try { return topicmap.search(query, new TopicMapSearchOptions(true, false, false, false, false)); } catch(Exception e) { e.printStackTrace(); } return new ArrayList<Topic>(); } public static String trimNonAlphaNums(String word) { if(word == null || word.length() < 1) return ""; int i=0; int j=word.length()-1; for(; i<word.length() && !Character.isLetterOrDigit(word.charAt(i)); i++); for(; j>i+1 && !Character.isLetterOrDigit(word.charAt(j)); j--); return word.substring(i,j+1); } public static String encodeURL(String s) { if(s != null) { return encodeURL(s, "UTF-8"); } return null; } public static String encodeURL(String s, String enc) { try { if(s != null && enc != null) { return java.net.URLEncoder.encode(s, enc); } } catch (Exception e) { e.printStackTrace(); return s; } return ""; } public static String decodeURL(String s) { return decodeURL(s, "UTF-8"); } public static String decodeURL(String s, String enc) { try { if(s != null) { return java.net.URLDecoder.decode(s, enc); } } catch (Exception e) { e.printStackTrace(); return s; } return ""; } public static String populateLinks(String text, String linkTemplate) { if(text != null && text.length()>0) { String DELIMITERS = " \n\t',.\""; StringBuffer newText = new StringBuffer(1000); String searchword; String link; String substring; int index=0; int wordStart; int wordEnd; while(index < text.length()) { while(index < text.length() && DELIMITERS.indexOf(text.charAt(index)) != -1) { newText.append(text.charAt(index)); index++; } // pass html/xml tags while(index < text.length() && text.charAt(index) == '<') { while(index < text.length() && text.charAt(index) != '>') { newText.append(text.charAt(index)); index++; } newText.append(text.charAt(index)); index++; } // potential word found wordStart=index; while(index < text.length() && DELIMITERS.indexOf(text.charAt(index)) == -1 && text.charAt(index) != '<') { index++; } if(index > wordStart) { substring = text.substring(wordStart, index); // try { substring = encodeHTML(substring); } catch (Exception e) {} if(index-wordStart > 3) { searchword = trimNonAlphaNums(substring); if(searchword.length() > 3) { link = linkTemplate.replaceAll("%searchw%", encodeURL(searchword)); link = link.replaceAll("%word%", substring); newText.append(link); } else { newText.append(substring); } } else { newText.append(substring); } } } text = newText.toString(); } return text; } public static class TreeNode { public Topic content; public boolean openChildren; public boolean closeChildren; public TreeNode(Topic content,boolean openChildren,boolean closeChildren){ this.content=content; this.openChildren=openChildren; this.closeChildren=closeChildren; } } public static ArrayList<String> capitalizeFirst(List<String> words) { ArrayList<String> newWords = new ArrayList<String>(); if (words != null) { for (int i=0; i<words.size(); i++) { newWords.add(capitalizeFirst(words.get(i))); } } return newWords; } public static String capitalizeFirst(String word) { boolean shouldCapitalize = true; if(word != null) { for (int i=0; i<word.length() && shouldCapitalize; i++) { if(Character.isLetter(word.charAt(i)) && shouldCapitalize) { try { word = word.substring(0, i) + (Character.toUpperCase(word.charAt(i))) + word.substring(i+1, word.length()); shouldCapitalize = false; } catch (Exception e) { e.printStackTrace(); } } } } return word; } public static String capitalizeFirsts(String word) { StringBuffer newWord = new StringBuffer(); boolean shouldCapitalize = true; if (word != null) { for (int i=0; i<word.length(); i++) { if (Character.isLetter(word.charAt(i)) && shouldCapitalize) { newWord.append(Character.toUpperCase(word.charAt(i))); shouldCapitalize = false; } else if (!Character.isLetter(word.charAt(i))) { newWord.append(word.charAt(i)); shouldCapitalize = true; } else newWord.append(word.charAt(i)); } } return newWord.toString(); } public static boolean urlExists(String urlString) { if(urlString != null) { try { if(IObox.urlExists(new URL(urlString))) return true; } catch (Exception e) {} } return false; } public static Collection<Association> sortAssociationsWithPlayer(Collection<Association> associations, Topic sortRole, String lang) { ArrayList<Association> al = new ArrayList<Association>(associations); Collections.sort(al, new TMBox.AssociationPlayerComparator(sortRole,lang)); return al; /* Vector<Association> sortedAssociations = new Vector(); if(associations == null || sortRole == null || lang == null ) return sortedAssociations; Vector<Topic> playersCleaned = new Vector(); Collection players = null; Iterator<Association> iter = associations.iterator(); Iterator<Topic> playerIter = null; Association association = null; Topic player = null; // First collects all players while(iter.hasNext()) { try { association = iter.next(); if(association != null && !association.isRemoved()) { player = association.getPlayer(sortRole); if(!playersCleaned.contains(player)) playersCleaned.add(player); } } catch(Exception e) { e.printStackTrace(); } } Vector<Topic> tempPlayers = new Vector(); tempPlayers.addAll( TMBox.sortTopics(playersCleaned, lang) ); // Then iterate through sorted players and pick topics that have the player topic // as a player... Topic cleanPlayer = null; int s = tempPlayers.size(); for(int i=0; i<s; i++) { cleanPlayer = tempPlayers.elementAt(i); iter = associations.iterator(); while(iter.hasNext()) { try { association = iter.next(); if(association != null && !association.isRemoved()) { player = association.getPlayer(sortRole); if(player.mergesWithTopic(cleanPlayer)) { sortedAssociations.add(association); } } } catch(Exception e) { e.printStackTrace(); } } } // Finally add all remainding topics to sorted array.... iter = associations.iterator(); while(iter.hasNext()) { try { association = iter.next(); if(association != null && !association.isRemoved()) { if(!sortedAssociations.contains(association)) { sortedAssociations.add(association); } } } catch(Exception e) { e.printStackTrace(); } } return sortedAssociations;*/ } public static Collection<Topic> sortTopicsWithOccurrence(Collection<Topic> topics, Topic occurrenceType, String lang) { return sortTopicsWithOccurrence(topics, occurrenceType, lang, "false"); } public static Collection<Topic> sortTopicsWithOccurrence(Collection<Topic> topics, Topic occurrenceType, String lang, String desc) { if(occurrenceType != null && lang != null) { try { return TMBox.sortTopicsByData(topics, occurrenceType, lang, (desc.equalsIgnoreCase("true") ? true : false)); } catch(Exception e) { // } } return topics; } public static Collection<Topic> sortTopics(Collection<Topic> topics, String lang) { return TMBox.sortTopics(topics, lang); } public static Collection<Topic> sortTopicsWithPlayer(Collection<Topic> topics, Topic associationType, Topic role, String lang) { List<Topic> al=new ArrayList<Topic>(topics); Collections.sort(al,new TMBox.TopicAssociationPlayerComparator(associationType,role,lang)); return al; /* Vector<Topic> sortedTopics = new Vector(); if(topics == null || associationType == null || role == null || lang == null ) return sortedTopics; Vector<Topic> playersCleaned = new Vector(); Collection players = null; Iterator<Topic> iter = topics.iterator(); Iterator<Topic> playerIter = null; Topic topic = null; Topic player = null; // First collects all players while(iter.hasNext()) { try { topic = iter.next(); if(topic != null && !topic.isRemoved()) { players = getPlayers(topic, associationType, role); playerIter = players.iterator(); while(playerIter.hasNext()) { player = playerIter.next(); if(!playersCleaned.contains(player)) playersCleaned.add(player); } } } catch(Exception e) { e.printStackTrace(); } } Vector<Topic> tempPlayers = new Vector(); tempPlayers.addAll( TMBox.sortTopics(playersCleaned, lang) ); // Then iterate through sorted players and pick topics that have the player topic // as a player... Topic cleanPlayer = null; int s = tempPlayers.size(); for(int i=0; i<s; i++) { cleanPlayer = tempPlayers.elementAt(i); iter = topics.iterator(); while(iter.hasNext()) { try { topic = iter.next(); if(topic != null && !topic.isRemoved()) { players = getPlayers(topic, associationType, role); if(players.contains(cleanPlayer) && !sortedTopics.contains(topic)) { sortedTopics.add(topic); } } } catch(Exception e) { e.printStackTrace(); } } } // Finally add all remainding topics to sorted array.... iter = topics.iterator(); while(iter.hasNext()) { try { topic = iter.next(); if(topic != null && !topic.isRemoved()) { if(!sortedTopics.contains(topic)) { sortedTopics.add(topic); } } } catch(Exception e) { e.printStackTrace(); } } return sortedTopics;*/ } public static <K> Collection<K> reverseOrder(Collection<K> objects) { if(objects != null) { List<K> reversedList = new ArrayList<K>(); reversedList.addAll(objects); Collections.reverse(reversedList); return reversedList; } return null; } // ------------------------------------------------------------------------- public static String composeLinearTopicNameString(Collection<Topic> topics, String lang, String delimiter) { return composeLinearTopicNameString(topics, lang, delimiter, ""); } public static String composeLinearTopicNameString(Collection<Topic> topics, String lang, String delimiter, String extraSettings) { StringBuffer sb = new StringBuffer(""); if(delimiter == null) delimiter = ""; if(lang == null) lang = "en"; if(topics != null && topics.size() > 0) { for(Iterator<Topic> iter = topics.iterator(); iter.hasNext(); ) { try { Topic t = (Topic) iter.next(); String name = t.getDisplayName(lang); if(extraSettings != null && extraSettings.indexOf("SWAP_ORDER") != -1) name = firstNameFirst(name); sb.append(name); if(iter.hasNext()) sb.append(delimiter); } catch (Exception e) { e.printStackTrace(); } } } return sb.toString(); } public static String makeHTML(String s) { if(s != null && s.length() > 0) { s = s.replaceAll("\\n", "<br>"); } return s; } public static String changeStringEncoding(String s, String sourceenc, String targetenc) { if(s != null && targetenc != null && sourceenc != null) { try { return new String( s.getBytes(sourceenc), targetenc ); } catch (Exception e) { e.printStackTrace(); } } return s; } public static String firstNameFirst(String name) { return Textbox.firstNameFirst(name); } public static String lastNameFirst(String name) { return Textbox.reverseName(name); } public static String smartSubstring(String s, int len) { if(s != null && s.length() > len) { s = s.substring(0, len); int si = s.lastIndexOf(' '); if(si > len/2) { s = s.substring(0, si); } s = s + "..."; } return s; } public static int makeInt(String number) { try { return Integer.parseInt(number); } catch(Exception e) {} return 0; } // Helper method to get date integers .... public static int currentYear() { Calendar rightNow = Calendar.getInstance(); return rightNow.get(Calendar.YEAR) - 1900; } public static int currentMonth() { Calendar rightNow = Calendar.getInstance(); return rightNow.get(Calendar.MONTH); } public static int currentDate() { Calendar rightNow = Calendar.getInstance(); return rightNow.get(Calendar.DAY_OF_MONTH); } public static int currentDay() { Calendar rightNow = Calendar.getInstance(); return rightNow.get(Calendar.DAY_OF_WEEK); } // --------------------------------------------------------------- SORT --- public static <T extends Comparable> List<T> sort(List<T> list) { Collections.sort(list); return list; } }
60,238
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TextBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/velocity/TextBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * TextBox.java * * Created on July 13, 2004, 9:17 AM */ package org.wandora.utils.velocity; import java.util.Properties; /** * * @author olli */ public class TextBox { public static final String PROP_SHORTNAMELENGTH="textbox.shortnamelength"; private int shortNameLength; public TextBox(){ this(new Properties()); } /** Creates a new instance of TextBox */ public TextBox(Properties properties) { shortNameLength=30; if(properties.getProperty(PROP_SHORTNAMELENGTH)!=null) shortNameLength=Integer.parseInt(properties.getProperty(PROP_SHORTNAMELENGTH)); } public String shortenName(String name){ if(name.length()<=shortNameLength) return name; else return name.substring(0,shortNameLength/2-2)+"..."+name.substring(name.length()-shortNameLength/2-2); } public String charToStr(int c){ return Character.valueOf((char)c).toString(); } public String repeat(String s,int times){ String r=""; for(int i=0;i<times;i++){ r+=s; } return r; } }
1,944
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TransferableImage.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/transferables/TransferableImage.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.utils.transferables; import java.awt.Image; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; /** * * @author akivela */ public class TransferableImage implements Transferable { private Image transferableImage = null; private String transferableString = null; public TransferableImage( Image transferableImage ) { this.transferableImage = transferableImage; } public TransferableImage( Image transferableImage, String transferableString ) { this.transferableImage = transferableImage; this.transferableString = transferableString; } @Override public Object getTransferData( DataFlavor flavor ) throws UnsupportedFlavorException, IOException { if(flavor.equals( DataFlavor.imageFlavor ) && transferableImage != null) { return transferableImage; } else if(flavor.equals( DataFlavor.stringFlavor ) && transferableString != null) { return transferableString; } else { throw new UnsupportedFlavorException( flavor ); } } @Override public DataFlavor[] getTransferDataFlavors() { DataFlavor[] flavors = null; if(transferableString != null) { flavors = new DataFlavor[2]; flavors[0] = DataFlavor.imageFlavor; flavors[1] = DataFlavor.stringFlavor; } else { flavors = new DataFlavor[1]; flavors[0] = DataFlavor.imageFlavor; } return flavors; } @Override public boolean isDataFlavorSupported( DataFlavor flavor ) { DataFlavor[] flavors = getTransferDataFlavors(); for( int i = 0; i < flavors.length; i++) { if( flavor.equals( flavors[ i ] )) { return true; } } return false; } }
2,805
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TransferableDataURL.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/transferables/TransferableDataURL.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.wandora.utils.transferables; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.nio.ByteBuffer; import org.wandora.utils.Base64; import org.wandora.utils.DataURL; /** * * @author akivela */ public class TransferableDataURL implements Transferable { private DataURL transferableData = null; public TransferableDataURL( DataURL transferableData ) { this.transferableData = transferableData; } @Override public Object getTransferData( DataFlavor flavor ) throws UnsupportedFlavorException, IOException { if(transferableData != null) { if(flavor.getMimeType().contains(transferableData.getMimetype())) { return transferableData.getData(); } else if(flavor.equals( DataFlavor.stringFlavor )) { return transferableData.toExternalForm(Base64.DONT_BREAK_LINES); } else if(flavor.isRepresentationClassByteBuffer()) { return ByteBuffer.wrap(transferableData.getData()); } else { // Warning, returning dataurl as a string if flavor is not recognized. return transferableData.toExternalForm(Base64.DONT_BREAK_LINES); } } throw new UnsupportedFlavorException( flavor ); } @Override public DataFlavor[] getTransferDataFlavors() { DataFlavor[] flavors = null; if(transferableData != null) { try { flavors = new DataFlavor[2]; flavors[0] = new DataURLFlavor(transferableData.getMimetype()); flavors[1] = DataFlavor.stringFlavor; return flavors; } catch(Exception e) { e.printStackTrace(); } } flavors = new DataFlavor[0]; return flavors; } @Override public boolean isDataFlavorSupported( DataFlavor flavor ) { DataFlavor[] flavors = getTransferDataFlavors(); for( int i = 0; i < flavors.length; i++) { if( flavor.equals( flavors[ i ] )) { return true; } } return false; } // ------------------------------------------------------ DataURLFlavor ---- public class DataURLFlavor extends DataFlavor { public DataURLFlavor(String mimeType) throws ClassNotFoundException { super(mimeType); } @Override public Class getRepresentationClass() { try { Class c = Class.forName("[B"); // byte array i.e. byte[] return c; } catch(Exception e) { e.printStackTrace(); } return null; } } }
3,739
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z