diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/queries/java/com/metabroadcast/atlas/glycerin/generator/FeedQueryGenerator.java b/src/queries/java/com/metabroadcast/atlas/glycerin/generator/FeedQueryGenerator.java index 0f0b070..9f5ded9 100644 --- a/src/queries/java/com/metabroadcast/atlas/glycerin/generator/FeedQueryGenerator.java +++ b/src/queries/java/com/metabroadcast/atlas/glycerin/generator/FeedQueryGenerator.java @@ -1,362 +1,362 @@ package com.metabroadcast.atlas.glycerin.generator; import static com.google.common.base.Preconditions.checkState; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.LocalDate; import com.metabroadcast.atlas.glycerin.model.Feed; import com.metabroadcast.atlas.glycerin.model.Filter; import com.metabroadcast.atlas.glycerin.model.Mixin; import com.metabroadcast.atlas.glycerin.model.Option; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.metabroadcast.atlas.glycerin.queries.BaseApiQuery; import com.sun.codemodel.internal.JBlock; import com.sun.codemodel.internal.JClass; import com.sun.codemodel.internal.JClassAlreadyExistsException; import com.sun.codemodel.internal.JCodeModel; import com.sun.codemodel.internal.JDefinedClass; import com.sun.codemodel.internal.JEnumConstant; import com.sun.codemodel.internal.JExpr; import com.sun.codemodel.internal.JFieldVar; import com.sun.codemodel.internal.JInvocation; import com.sun.codemodel.internal.JMethod; import com.sun.codemodel.internal.JMod; import com.sun.codemodel.internal.JPackage; import com.sun.codemodel.internal.JType; import com.sun.codemodel.internal.JVar; public class FeedQueryGenerator { private static final int privateStaticFinal = JMod.PRIVATE|JMod.STATIC|JMod.FINAL; private static final String MODEL_PKG = "com.metabroadcast.atlas.glycerin.model."; private final JCodeModel model; private final JPackage pkg; private final JClass parent; private final JClass precs; private final JClass immutableList; private final JClass immutableMap; private final JClass immutableMapBldr; private static final ImmutableMap<String, Class<?>> typeMap = ImmutableMap.<String, Class<?>>builder() .put("integer", Integer.class) .put("datetime", DateTime.class) .put("string", String.class) .put("ID", String.class) .put("PID", String.class) .put("character", Character.class) .put("boolean", Boolean.class) .put("date", LocalDate.class) .build(); public FeedQueryGenerator(JCodeModel model, JPackage pkg) { this.model = model; this.pkg = pkg; this.parent = model.directClass(BaseApiQuery.class.getCanonicalName()); this.precs = model.directClass(Preconditions.class.getCanonicalName()); this.immutableList = model.directClass(ImmutableList.class.getCanonicalName()); this.immutableMap = model.directClass(ImmutableMap.class.getCanonicalName()); this.immutableMapBldr = model.directClass(ImmutableMap.Builder.class.getCanonicalName()) .narrow(String.class, Object.class); } public void generateQuery(Feed feed) { try { JClass transformedType = getTransformedType(feed); if (transformedType == null) { return; } JDefinedClass cls = pkg._class(JMod.PUBLIC|JMod.FINAL, String.format("%sQuery", feed.getName())); cls._extends(parent.narrow(transformedType)); if (feed.getTitle()!=null) { cls.javadoc().add(String.format("<p>%s</p>",feed.getTitle())); } addResourcePath(cls, feed); addResultTypeMethod(model, cls, transformedType); addContstructor(cls); JDefinedClass bldrCls = addBuilderCls(feed, cls); cls.method(JMod.PUBLIC|JMod.STATIC|JMod.FINAL, bldrCls, "builder") .body()._return(JExpr._new(bldrCls)); } catch (Exception e) { throw new IllegalStateException(e); } } private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls) throws JClassAlreadyExistsException, ClassNotFoundException { JDefinedClass bldrCls = cls._class(JMod.PUBLIC|JMod.STATIC|JMod.FINAL, "Builder"); JVar paramBuilder = bldrCls.field(JMod.PRIVATE|JMod.FINAL, immutableMapBldr, "params") .init(immutableMap.staticInvoke("builder")); for (Filter filter : feed.getFilters().getFilter()) { if (!Boolean.TRUE.equals(filter.isDeprecated())) { addWithersFor(filter, bldrCls, paramBuilder); } } if (feed.getMixins() != null && feed.getMixins().getMixin() != null) { JDefinedClass mixinEnum = getMixinEnum(feed); for (Mixin mixin : feed.getMixins().getMixin()) { String mixinName = mixin.getName().toUpperCase().replace(' ', '_'); JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName); mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+'))); } - JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXINS"); - field.init(JExpr.lit("mixins")); + JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXIN"); + field.init(JExpr.lit("mixin")); JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); JVar param = iterWither.param(iterable(mixinEnum), "mixins"); JBlock mthdBody = iterWither.body(); mthdBody.add(paramBuilder.invoke("put") .arg(field) .arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); param = varArgWither.varParam(mixinEnum, "mixins"); varArgWither.body()._return(JExpr.invoke(iterWither) .arg(immutableList.staticInvoke("copyOf").arg(param))); } JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build"); bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build"))); //TODO: add sorts return bldrCls; } private JDefinedClass getMixinEnum(Feed feed) throws JClassAlreadyExistsException { String enumName = camel(feed.getName(), true) + "Mixin"; if (pkg.isDefined(enumName)) { return pkg._getClass(enumName); } JDefinedClass valueEnum = pkg._enum(enumName); JFieldVar valField = valueEnum.field(JMod.PRIVATE|JMod.FINAL, String.class, "value"); JMethod ctor = valueEnum.constructor(JMod.PRIVATE); JVar param = ctor.param(String.class, "val"); ctor.body().assign(valField, param); JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(Override.class); toString.body()._return(valField); return valueEnum; } private void addContstructor(JDefinedClass cls) { JMethod constructor = cls.constructor(JMod.PRIVATE); constructor.param(stringObjectMap(model), "params"); constructor.body().invoke("super") .arg(constructor.listParams()[0]); } private JClass getTransformedType(Feed feed) { Class<?> cls = null; String name = feed.getName(); cls = tryLoadClass(MODEL_PKG + name); if (cls == null) {//attempt in possible naive singular. cls = tryLoadClass(MODEL_PKG + name.substring(0, name.length()-1)); } if (cls == null) { cls = Object.class; } return model.ref(cls); } private Class<?> tryLoadClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } private JClass stringObjectMap(JCodeModel model) { return model.ref(Map.class).narrow(String.class, Object.class); } private void addWithersFor(Filter filter, JDefinedClass bldrCls, JVar paramBuilder) throws ClassNotFoundException, JClassAlreadyExistsException { JDefinedClass cls = (JDefinedClass) bldrCls.parentContainer(); JFieldVar field = cls.field(privateStaticFinal, String.class, filter.getName().toUpperCase()); field.init(JExpr.lit(filter.getName())); JClass paramType = mapType(filter); if (Boolean.TRUE.equals(filter.isMultipleValues())) { JMethod iterableWither = addIterableWither(filter, bldrCls, paramBuilder, field, paramType); addVarArgsWither(filter, iterableWither, bldrCls, paramType); } else { addWither(filter, bldrCls, paramBuilder, field, paramType); } } private void addVarArgsWither(Filter filter, JMethod wither, JDefinedClass bldrCls, JClass paramType) throws JClassAlreadyExistsException { JMethod method = bldrCls.method(wither.mods().getValue(), wither.type(), wither.name()); if (filter.getTitle()!=null) { method.javadoc().add(String.format("<p>%s</p>",filter.getTitle())); } JVar param = method.varParam(paramType, wither.listParams()[0].name()); method.body()._return(JExpr.invoke(wither).arg(immutableList.staticInvoke("copyOf").arg(param))); } private void addWither(Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType) throws JClassAlreadyExistsException { JMethod method = createWitherMethod(filter, bldrCls); if (filter.getTitle()!=null) { method.javadoc().add(String.format("<p>%s</p>",filter.getTitle())); } JVar param = addParam(filter, method, paramType); JBlock mthdBody = method.body(); boolean needsNullCheck = true; if (filter.getMinValue() != null) { mthdBody.add(precs.staticInvoke("checkNotNull").arg(param)); needsNullCheck = false; int min = filter.getMinValue().intValue(); mthdBody.add(precs.staticInvoke("checkArgument") .arg(JExpr.lit(min).lte(param)) .arg(JExpr.lit(param.name() + ": %s < " + min)) .arg(param) ); } if (filter.getMaxValue() != null) { if (needsNullCheck) { mthdBody.add(precs.staticInvoke("checkNotNull").arg(param)); needsNullCheck = false; } int max = filter.getMaxValue().intValue(); mthdBody.add(precs.staticInvoke("checkArgument") .arg(JExpr.lit(max).gte(param)) .arg(JExpr.lit(param.name() + ": %s > " + max)) .arg(param) ); } JInvocation putIntoMap = paramBuilder.invoke("put") .arg(field); if (needsNullCheck) { putIntoMap.arg(precs.staticInvoke("checkNotNull").arg(param)); } else { putIntoMap.arg(param); } mthdBody.add(putIntoMap); mthdBody._return(JExpr._this()); } private JMethod addIterableWither(Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType) throws JClassAlreadyExistsException { JMethod method = createWitherMethod(filter, bldrCls); if (filter.getTitle()!=null) { method.javadoc().add(String.format("<p>%s</p>",filter.getTitle())); } JVar param = addParam(filter, method, iterable(paramType)); JBlock mthdBody = method.body(); mthdBody.add(paramBuilder.invoke("put") .arg(field) .arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); return method; } private JVar addParam(Filter filter, JMethod method, JType paramType) { return method.param(paramType, camel(filter.getName(), false)); } private JMethod createWitherMethod(Filter filter, JDefinedClass bldrCls) { String filterMethodName = "with" + camel(filter.getName(), true); return bldrCls.method(JMod.PUBLIC, bldrCls, filterMethodName); } private JType iterable(JClass mapType) { return model.directClass("Iterable").narrow(mapType); } private JClass mapType(Filter filter) throws JClassAlreadyExistsException { if (!(filter.getOption() == null || filter.getOption().isEmpty())){ return getParamTypeEnum(filter); } String type = filter.getType(); Class<?> typeCls = typeMap.get(type); checkState(typeCls != null, "Unexpected type: %s", type); return model.ref(typeCls); } private JClass getParamTypeEnum(Filter filter) throws JClassAlreadyExistsException { String enumName = camel(filter.getName(), true) + "Option"; if (pkg.isDefined(enumName)) { return pkg._getClass(enumName); } List<Option> options = filter.getOption(); if (options.size() == 1) {/*turn into '*Only' method?*/} if (options.size() == 2) { if (ImmutableSet.of("true","false").equals( ImmutableSet.of(options.get(0).getValue().toLowerCase(), options.get(1).getValue().toLowerCase() ) )) { return model.ref(Boolean.class); } } JDefinedClass valueEnum = pkg._enum(enumName); JFieldVar valField = valueEnum.field(JMod.PRIVATE|JMod.FINAL, String.class, "value"); JMethod ctor = valueEnum.constructor(JMod.PRIVATE); JVar param = ctor.param(String.class, "val"); ctor.body().assign(valField, param); JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(Override.class); toString.body()._return(valField); for (Option option : options) { String optionName = option.getValue().toUpperCase().replace(' ', '_'); JEnumConstant optionCst = valueEnum.enumConstant(optionName); optionCst.arg(JExpr.lit(option.getValue().replace(' ', '+'))); } return valueEnum; } private String camel(String name, boolean upperInitial) { char initial = name.charAt(0); StringBuilder converted = new StringBuilder() .append(upperInitial ? Character.toUpperCase(initial) : initial); for (int i = 1; i < name.length(); i++) { char chr = name.charAt(i); if (chr == '_' && i+1 < name.length()) { converted.append(Character.toUpperCase(name.charAt(++i))); } else { converted.append(chr); } } return converted.toString(); } private void addResultTypeMethod(JCodeModel model, JDefinedClass cls, JClass transformedType) { JClass classCls = model.ref(Class.class); JMethod method = cls.method(JMod.PROTECTED|JMod.FINAL, classCls.narrow(transformedType), "resultsType"); method.body()._return(JExpr.dotclass(transformedType)); method.annotate(Override.class); } private void addResourcePath(JDefinedClass cls, Feed feed) { JFieldVar field = cls.field(privateStaticFinal, String.class, "RESOURCE_PATH"); field.init(JExpr.lit(feed.getHref())); JMethod method = cls.method(JMod.PROTECTED|JMod.FINAL, String.class, "resourcePath"); method.annotate(Override.class); method.body()._return(field); } }
true
true
private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls) throws JClassAlreadyExistsException, ClassNotFoundException { JDefinedClass bldrCls = cls._class(JMod.PUBLIC|JMod.STATIC|JMod.FINAL, "Builder"); JVar paramBuilder = bldrCls.field(JMod.PRIVATE|JMod.FINAL, immutableMapBldr, "params") .init(immutableMap.staticInvoke("builder")); for (Filter filter : feed.getFilters().getFilter()) { if (!Boolean.TRUE.equals(filter.isDeprecated())) { addWithersFor(filter, bldrCls, paramBuilder); } } if (feed.getMixins() != null && feed.getMixins().getMixin() != null) { JDefinedClass mixinEnum = getMixinEnum(feed); for (Mixin mixin : feed.getMixins().getMixin()) { String mixinName = mixin.getName().toUpperCase().replace(' ', '_'); JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName); mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+'))); } JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXINS"); field.init(JExpr.lit("mixins")); JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); JVar param = iterWither.param(iterable(mixinEnum), "mixins"); JBlock mthdBody = iterWither.body(); mthdBody.add(paramBuilder.invoke("put") .arg(field) .arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); param = varArgWither.varParam(mixinEnum, "mixins"); varArgWither.body()._return(JExpr.invoke(iterWither) .arg(immutableList.staticInvoke("copyOf").arg(param))); } JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build"); bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build"))); //TODO: add sorts return bldrCls; }
private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls) throws JClassAlreadyExistsException, ClassNotFoundException { JDefinedClass bldrCls = cls._class(JMod.PUBLIC|JMod.STATIC|JMod.FINAL, "Builder"); JVar paramBuilder = bldrCls.field(JMod.PRIVATE|JMod.FINAL, immutableMapBldr, "params") .init(immutableMap.staticInvoke("builder")); for (Filter filter : feed.getFilters().getFilter()) { if (!Boolean.TRUE.equals(filter.isDeprecated())) { addWithersFor(filter, bldrCls, paramBuilder); } } if (feed.getMixins() != null && feed.getMixins().getMixin() != null) { JDefinedClass mixinEnum = getMixinEnum(feed); for (Mixin mixin : feed.getMixins().getMixin()) { String mixinName = mixin.getName().toUpperCase().replace(' ', '_'); JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName); mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+'))); } JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXIN"); field.init(JExpr.lit("mixin")); JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); JVar param = iterWither.param(iterable(mixinEnum), "mixins"); JBlock mthdBody = iterWither.body(); mthdBody.add(paramBuilder.invoke("put") .arg(field) .arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); param = varArgWither.varParam(mixinEnum, "mixins"); varArgWither.body()._return(JExpr.invoke(iterWither) .arg(immutableList.staticInvoke("copyOf").arg(param))); } JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build"); bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build"))); //TODO: add sorts return bldrCls; }
diff --git a/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/commands/clan/bb/BBCommand.java b/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/commands/clan/bb/BBCommand.java index 9f407a1..515fe98 100644 --- a/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/commands/clan/bb/BBCommand.java +++ b/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/commands/clan/bb/BBCommand.java @@ -1,82 +1,82 @@ /* * This file is part of SimpleClans2 (2012). * * SimpleClans2 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. * * SimpleClans2 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 SimpleClans2. If not, see <http://www.gnu.org/licenses/>. * * Last modified: 10.10.12 21:57 */ package com.p000ison.dev.simpleclans2.commands.clan.bb; import com.p000ison.dev.simpleclans2.SimpleClans; import com.p000ison.dev.simpleclans2.api.chat.ChatBlock; import com.p000ison.dev.simpleclans2.api.clan.Clan; import com.p000ison.dev.simpleclans2.api.clanplayer.ClanPlayer; import com.p000ison.dev.simpleclans2.commands.CraftCommandManager; import com.p000ison.dev.simpleclans2.commands.GenericPlayerCommand; import com.p000ison.dev.simpleclans2.database.response.responses.BBRetrieveResponse; import com.p000ison.dev.simpleclans2.language.Language; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.text.MessageFormat; /** * Represents a BBCommand */ public class BBCommand extends GenericPlayerCommand { public BBCommand(SimpleClans plugin) { super("BB", plugin); setArgumentRange(0, 1); setUsages(MessageFormat.format(Language.getTranslation("usage.bb"), plugin.getSettingsManager().getBBCommand())); setIdentifiers(Language.getTranslation("bb.command")); setPermission("simpleclans.member.bb"); setType(Type.BB); } @Override public String getMenu(ClanPlayer cp) { if (cp != null && cp.getClan().isVerified()) { return MessageFormat.format(Language.getTranslation("menu.bb.view"), plugin.getSettingsManager().getBBCommand()); } return null; } @Override public void execute(Player player, String[] args) { ClanPlayer cp = plugin.getClanPlayerManager().getClanPlayer(player); if (cp == null) { - ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("clan.is.not.verified")); + ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("not.a.member.of.any.clan")); return; } Clan clan = cp.getClan(); if (!clan.isVerified()) { - ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("not.a.member.of.any.clan")); + ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("clan.is.not.verified")); return; } int page = CraftCommandManager.getPage(args); if (page == -1) { ChatBlock.sendMessage(player, Language.getTranslation("number.format")); return; } plugin.getDataManager().addResponse(new BBRetrieveResponse(plugin, player, clan, page, -1, true)); } }
false
true
public void execute(Player player, String[] args) { ClanPlayer cp = plugin.getClanPlayerManager().getClanPlayer(player); if (cp == null) { ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("clan.is.not.verified")); return; } Clan clan = cp.getClan(); if (!clan.isVerified()) { ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("not.a.member.of.any.clan")); return; } int page = CraftCommandManager.getPage(args); if (page == -1) { ChatBlock.sendMessage(player, Language.getTranslation("number.format")); return; } plugin.getDataManager().addResponse(new BBRetrieveResponse(plugin, player, clan, page, -1, true)); }
public void execute(Player player, String[] args) { ClanPlayer cp = plugin.getClanPlayerManager().getClanPlayer(player); if (cp == null) { ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("not.a.member.of.any.clan")); return; } Clan clan = cp.getClan(); if (!clan.isVerified()) { ChatBlock.sendMessage(player, ChatColor.RED + Language.getTranslation("clan.is.not.verified")); return; } int page = CraftCommandManager.getPage(args); if (page == -1) { ChatBlock.sendMessage(player, Language.getTranslation("number.format")); return; } plugin.getDataManager().addResponse(new BBRetrieveResponse(plugin, player, clan, page, -1, true)); }
diff --git a/src/main/java/spj/database/program/ProgramMapper.java b/src/main/java/spj/database/program/ProgramMapper.java index c28723f..ce2c99e 100644 --- a/src/main/java/spj/database/program/ProgramMapper.java +++ b/src/main/java/spj/database/program/ProgramMapper.java @@ -1,72 +1,72 @@ package spj.database.program; import com.google.common.collect.ImmutableList; import spj.database.SpjDomainMap; import spj.database.SpjDomainModelEntity; import spj.database.SpjDomainModelMapper; import spj.database.glavniprogram.GlavniProgramEntity; import spj.shared.domain.GlavniProgram; import spj.shared.domain.Program; import spj.shared.domain.SpjDomainModel; import spj.shared.util.SpjAssert; import spj.util.CastTool; import java.util.List; public class ProgramMapper implements SpjDomainModelMapper{ @Override public <T extends SpjDomainModel> List<T> createDomainModel(Iterable<? extends SpjDomainModelEntity> spjDomainModelEntityList) { SpjAssert.isNotNull(spjDomainModelEntityList, "spjDomainModelEntityList"); ImmutableList.Builder<T> resultBuilder = ImmutableList.builder(); for (SpjDomainModelEntity spjDomainModelEntity : spjDomainModelEntityList) { T spjDomainModel = createDomainModel(spjDomainModelEntity); resultBuilder.add(spjDomainModel); } return resultBuilder.build(); } @Override public <T extends SpjDomainModel> T createDomainModel(SpjDomainModelEntity spjDomainModelEntity) { SpjAssert.isNotNull(spjDomainModelEntity, "spjDomainModelEntity"); ProgramEntity programEntity = CastTool.cast(spjDomainModelEntity); GlavniProgram glavniProgram = SpjDomainMap.GLAVNI_PROGRAM.getMapper().createDomainModel(programEntity.getGlavniProgramEntity()); return CastTool.cast(Program.builder() .id(programEntity.getId()) .naziv(programEntity.getNaziv()) .zakonskaOsnova(programEntity.getZakonskaOsnova()) .brojZaposlenih(programEntity.getBrojZaposlenih()) .glavniProgram(glavniProgram) .opis(programEntity.getOpis()) .opciCilj(programEntity.getOpciCilj()) .pokazateljUspijeha(programEntity.getPokazateljUspijeha()) .build()); } @Override public <T extends SpjDomainModelEntity> T createEntity(SpjDomainModel spjDomainModel) { SpjAssert.isNotNull(spjDomainModel, "spjDomainModel"); Program program = CastTool.cast(spjDomainModel); GlavniProgramEntity glavniProgramEntity = SpjDomainMap.GLAVNI_PROGRAM.getMapper().createEntity(program.getGlavniProgram()); ProgramEntity programEntity = new ProgramEntity(); programEntity.setId(program.getId()); programEntity.setNaziv(program.getNaziv()); programEntity.setZakonskaOsnova(program.getZakonskaOsnova()); programEntity.setBrojZaposlenih(program.getBrojZaposlenih()); programEntity.setGlavniProgramEntity(glavniProgramEntity); programEntity.setOpis(program.getOpis()); programEntity.setOpciCilj(program.getOpciCilj()); programEntity.setPokazateljUspijeha(program.getPokazateljUspijeha()); - return CastTool.cast(glavniProgramEntity); + return CastTool.cast(programEntity); } }
true
true
public <T extends SpjDomainModelEntity> T createEntity(SpjDomainModel spjDomainModel) { SpjAssert.isNotNull(spjDomainModel, "spjDomainModel"); Program program = CastTool.cast(spjDomainModel); GlavniProgramEntity glavniProgramEntity = SpjDomainMap.GLAVNI_PROGRAM.getMapper().createEntity(program.getGlavniProgram()); ProgramEntity programEntity = new ProgramEntity(); programEntity.setId(program.getId()); programEntity.setNaziv(program.getNaziv()); programEntity.setZakonskaOsnova(program.getZakonskaOsnova()); programEntity.setBrojZaposlenih(program.getBrojZaposlenih()); programEntity.setGlavniProgramEntity(glavniProgramEntity); programEntity.setOpis(program.getOpis()); programEntity.setOpciCilj(program.getOpciCilj()); programEntity.setPokazateljUspijeha(program.getPokazateljUspijeha()); return CastTool.cast(glavniProgramEntity); }
public <T extends SpjDomainModelEntity> T createEntity(SpjDomainModel spjDomainModel) { SpjAssert.isNotNull(spjDomainModel, "spjDomainModel"); Program program = CastTool.cast(spjDomainModel); GlavniProgramEntity glavniProgramEntity = SpjDomainMap.GLAVNI_PROGRAM.getMapper().createEntity(program.getGlavniProgram()); ProgramEntity programEntity = new ProgramEntity(); programEntity.setId(program.getId()); programEntity.setNaziv(program.getNaziv()); programEntity.setZakonskaOsnova(program.getZakonskaOsnova()); programEntity.setBrojZaposlenih(program.getBrojZaposlenih()); programEntity.setGlavniProgramEntity(glavniProgramEntity); programEntity.setOpis(program.getOpis()); programEntity.setOpciCilj(program.getOpciCilj()); programEntity.setPokazateljUspijeha(program.getPokazateljUspijeha()); return CastTool.cast(programEntity); }
diff --git a/src/main/java/org/bukkit/command/defaults/OpCommand.java b/src/main/java/org/bukkit/command/defaults/OpCommand.java index 76d6cc10..b8329de7 100644 --- a/src/main/java/org/bukkit/command/defaults/OpCommand.java +++ b/src/main/java/org/bukkit/command/defaults/OpCommand.java @@ -1,42 +1,42 @@ package org.bukkit.command.defaults; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class OpCommand extends VanillaCommand { public OpCommand() { super("op"); this.description = "Gives the specified player operator status"; this.usageMessage = "/op <player>"; this.setPermission("bukkit.command.op.give"); } @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length != 1) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } - Command.broadcastCommandMessage(sender, "Oping " + args[0]); + Command.broadcastCommandMessage(sender, "Opping " + args[0]); OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); player.setOp(true); if (player instanceof Player) { ((Player)player).sendMessage(ChatColor.YELLOW + "You are now op!"); } return true; } @Override public boolean matches(String input) { return input.startsWith("op ") || input.equalsIgnoreCase("op"); } }
true
true
public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length != 1) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } Command.broadcastCommandMessage(sender, "Oping " + args[0]); OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); player.setOp(true); if (player instanceof Player) { ((Player)player).sendMessage(ChatColor.YELLOW + "You are now op!"); } return true; }
public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length != 1) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } Command.broadcastCommandMessage(sender, "Opping " + args[0]); OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); player.setOp(true); if (player instanceof Player) { ((Player)player).sendMessage(ChatColor.YELLOW + "You are now op!"); } return true; }
diff --git a/src/main/java/com/turt2live/antishare/util/ASMaterialList.java b/src/main/java/com/turt2live/antishare/util/ASMaterialList.java index f218ca29..df0e7a51 100644 --- a/src/main/java/com/turt2live/antishare/util/ASMaterialList.java +++ b/src/main/java/com/turt2live/antishare/util/ASMaterialList.java @@ -1,200 +1,201 @@ /******************************************************************************* * Copyright (c) 2013 Travis Ralston. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * turt2live (Travis Ralston) - initial API and implementation ******************************************************************************/ package com.turt2live.antishare.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; import com.turt2live.antishare.AntiShare; import com.turt2live.antishare.io.ItemMap; /** * Material list for items * * @author turt2live */ public class ASMaterialList{ public static class ASMaterial{ public int id = 0; public short data = -1; // -1 = any public String name = "Unknown"; } private Map<Integer, List<ASMaterial>> listing = new HashMap<Integer, List<ASMaterial>>(); /** * Creates a new material list * * @param strings the list of strings */ public ASMaterialList(List<?> strings){ if(strings == null){ throw new IllegalArgumentException("Null arguments are not allowed"); } AntiShare p = AntiShare.p; for(Object o : strings){ if(!(o instanceof String)){ continue; } String s = (String) o; s = s.trim(); String testString = s.toLowerCase().replace(" ", ""); boolean negate = s.startsWith("-"); s = negate ? (s.replaceFirst("-", "").trim()) : s; if(s.equalsIgnoreCase("all")){ for(Material m : Material.values()){ ASMaterial asm = new ASMaterial(); asm.id = m.getId(); asm.data = -1; asm.name = m.name(); add(asm, negate); } continue; }else if(s.equalsIgnoreCase("none")){ listing.clear(); continue; }else if(testString.equalsIgnoreCase("furnace") || testString.equalsIgnoreCase("burningfurnace") || testString.equalsIgnoreCase(String.valueOf(Material.FURNACE.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.BURNING_FURNACE.getId()))){ add(Material.FURNACE, negate); add(Material.BURNING_FURNACE, negate); continue; }else if(testString.equalsIgnoreCase("sign") || testString.equalsIgnoreCase("wallsign") || testString.equalsIgnoreCase("signpost") || testString.equalsIgnoreCase(String.valueOf(Material.SIGN.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.WALL_SIGN.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.SIGN_POST.getId()))){ add(Material.SIGN, negate); add(Material.WALL_SIGN, negate); add(Material.SIGN_POST, negate); continue; }else if(testString.equalsIgnoreCase("brewingstand") || testString.equalsIgnoreCase("brewingstanditem") || testString.equalsIgnoreCase(String.valueOf(Material.BREWING_STAND.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.BREWING_STAND_ITEM.getId()))){ add(Material.BREWING_STAND, negate); add(Material.BREWING_STAND_ITEM, negate); continue; - }else if(testString.equalsIgnoreCase("enderportal") || testString.equalsIgnoreCase("enderportalframe") + }else if(testString.equalsIgnoreCase("endportal") || testString.equalsIgnoreCase("enderframe") || testString.equalsIgnoreCase("endframe") + || testString.equalsIgnoreCase("enderportal") || testString.equalsIgnoreCase("endportalframe") || testString.equalsIgnoreCase("enderportalframe") || testString.equalsIgnoreCase(String.valueOf(Material.ENDER_PORTAL.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.ENDER_PORTAL_FRAME.getId()))){ add(Material.ENDER_PORTAL, negate); add(Material.ENDER_PORTAL_FRAME, negate); continue; }else if(testString.equalsIgnoreCase("skull") || testString.equalsIgnoreCase("skullitem") || testString.equalsIgnoreCase("mobskull") || testString.equalsIgnoreCase(String.valueOf(Material.SKULL.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.SKULL_ITEM.getId()))){ add(Material.SKULL, negate); add(Material.SKULL_ITEM, negate); continue; } ASMaterial asm = ItemMap.get(s); if(asm == null){ p.getLogger().warning(p.getMessages().getMessage("unknown-material", s)); continue; } add(asm, negate); } } void add(ASMaterial m, boolean negate){ List<ASMaterial> materials = new ArrayList<ASMaterial>(); if(negate && m.data < 0){ listing.remove(m.id); return; } if(!negate){ materials.add(m); } if(listing.containsKey(m.id)){ if(negate){ for(ASMaterial m2 : listing.get(m.id)){ if(m.data != m2.data){ materials.add(m2); } } }else{ materials.addAll(listing.get(m.id)); } } listing.put(m.id, materials); } void add(Material m, boolean negate){ ASMaterial asm = new ASMaterial(); asm.id = m.getId(); asm.data = -1; asm.name = m.name(); add(asm, negate); } /** * Determines if this list has the material. Use {@link #has(Block)} or {@link #has(ItemStack)} where possible as this does not check the data value * * @param material the material * @return true if found */ public boolean has(Material material){ if(material == null){ return false; } return listing.containsKey(material.getId()); } /** * Determines if a block is contained in this list (item ID and data) * * @param block the block * @return true if found */ public boolean has(Block block){ if(block == null){ return false; } Material material = block.getType(); short data = block.getData(); return find(material, data); } /** * Determines if a item is contained in this list (item ID and data) * * @param item the item * @return true if found */ public boolean has(ItemStack item){ if(item == null){ return false; } Material material = item.getType(); short data = item.getDurability(); return find(material, data); } private boolean find(Material material, short data){ List<ASMaterial> asMaterials = listing.get(material.getId()); if(asMaterials == null){ return false; } for(ASMaterial m : asMaterials){ if(m.id == material.getId() && (m.data == data || m.data < 0)){ return true; } } return false; } }
true
true
public ASMaterialList(List<?> strings){ if(strings == null){ throw new IllegalArgumentException("Null arguments are not allowed"); } AntiShare p = AntiShare.p; for(Object o : strings){ if(!(o instanceof String)){ continue; } String s = (String) o; s = s.trim(); String testString = s.toLowerCase().replace(" ", ""); boolean negate = s.startsWith("-"); s = negate ? (s.replaceFirst("-", "").trim()) : s; if(s.equalsIgnoreCase("all")){ for(Material m : Material.values()){ ASMaterial asm = new ASMaterial(); asm.id = m.getId(); asm.data = -1; asm.name = m.name(); add(asm, negate); } continue; }else if(s.equalsIgnoreCase("none")){ listing.clear(); continue; }else if(testString.equalsIgnoreCase("furnace") || testString.equalsIgnoreCase("burningfurnace") || testString.equalsIgnoreCase(String.valueOf(Material.FURNACE.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.BURNING_FURNACE.getId()))){ add(Material.FURNACE, negate); add(Material.BURNING_FURNACE, negate); continue; }else if(testString.equalsIgnoreCase("sign") || testString.equalsIgnoreCase("wallsign") || testString.equalsIgnoreCase("signpost") || testString.equalsIgnoreCase(String.valueOf(Material.SIGN.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.WALL_SIGN.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.SIGN_POST.getId()))){ add(Material.SIGN, negate); add(Material.WALL_SIGN, negate); add(Material.SIGN_POST, negate); continue; }else if(testString.equalsIgnoreCase("brewingstand") || testString.equalsIgnoreCase("brewingstanditem") || testString.equalsIgnoreCase(String.valueOf(Material.BREWING_STAND.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.BREWING_STAND_ITEM.getId()))){ add(Material.BREWING_STAND, negate); add(Material.BREWING_STAND_ITEM, negate); continue; }else if(testString.equalsIgnoreCase("enderportal") || testString.equalsIgnoreCase("enderportalframe") || testString.equalsIgnoreCase(String.valueOf(Material.ENDER_PORTAL.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.ENDER_PORTAL_FRAME.getId()))){ add(Material.ENDER_PORTAL, negate); add(Material.ENDER_PORTAL_FRAME, negate); continue; }else if(testString.equalsIgnoreCase("skull") || testString.equalsIgnoreCase("skullitem") || testString.equalsIgnoreCase("mobskull") || testString.equalsIgnoreCase(String.valueOf(Material.SKULL.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.SKULL_ITEM.getId()))){ add(Material.SKULL, negate); add(Material.SKULL_ITEM, negate); continue; } ASMaterial asm = ItemMap.get(s); if(asm == null){ p.getLogger().warning(p.getMessages().getMessage("unknown-material", s)); continue; } add(asm, negate); } }
public ASMaterialList(List<?> strings){ if(strings == null){ throw new IllegalArgumentException("Null arguments are not allowed"); } AntiShare p = AntiShare.p; for(Object o : strings){ if(!(o instanceof String)){ continue; } String s = (String) o; s = s.trim(); String testString = s.toLowerCase().replace(" ", ""); boolean negate = s.startsWith("-"); s = negate ? (s.replaceFirst("-", "").trim()) : s; if(s.equalsIgnoreCase("all")){ for(Material m : Material.values()){ ASMaterial asm = new ASMaterial(); asm.id = m.getId(); asm.data = -1; asm.name = m.name(); add(asm, negate); } continue; }else if(s.equalsIgnoreCase("none")){ listing.clear(); continue; }else if(testString.equalsIgnoreCase("furnace") || testString.equalsIgnoreCase("burningfurnace") || testString.equalsIgnoreCase(String.valueOf(Material.FURNACE.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.BURNING_FURNACE.getId()))){ add(Material.FURNACE, negate); add(Material.BURNING_FURNACE, negate); continue; }else if(testString.equalsIgnoreCase("sign") || testString.equalsIgnoreCase("wallsign") || testString.equalsIgnoreCase("signpost") || testString.equalsIgnoreCase(String.valueOf(Material.SIGN.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.WALL_SIGN.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.SIGN_POST.getId()))){ add(Material.SIGN, negate); add(Material.WALL_SIGN, negate); add(Material.SIGN_POST, negate); continue; }else if(testString.equalsIgnoreCase("brewingstand") || testString.equalsIgnoreCase("brewingstanditem") || testString.equalsIgnoreCase(String.valueOf(Material.BREWING_STAND.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.BREWING_STAND_ITEM.getId()))){ add(Material.BREWING_STAND, negate); add(Material.BREWING_STAND_ITEM, negate); continue; }else if(testString.equalsIgnoreCase("endportal") || testString.equalsIgnoreCase("enderframe") || testString.equalsIgnoreCase("endframe") || testString.equalsIgnoreCase("enderportal") || testString.equalsIgnoreCase("endportalframe") || testString.equalsIgnoreCase("enderportalframe") || testString.equalsIgnoreCase(String.valueOf(Material.ENDER_PORTAL.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.ENDER_PORTAL_FRAME.getId()))){ add(Material.ENDER_PORTAL, negate); add(Material.ENDER_PORTAL_FRAME, negate); continue; }else if(testString.equalsIgnoreCase("skull") || testString.equalsIgnoreCase("skullitem") || testString.equalsIgnoreCase("mobskull") || testString.equalsIgnoreCase(String.valueOf(Material.SKULL.getId())) || testString.equalsIgnoreCase(String.valueOf(Material.SKULL_ITEM.getId()))){ add(Material.SKULL, negate); add(Material.SKULL_ITEM, negate); continue; } ASMaterial asm = ItemMap.get(s); if(asm == null){ p.getLogger().warning(p.getMessages().getMessage("unknown-material", s)); continue; } add(asm, negate); } }
diff --git a/access-impl/impl/src/java/org/sakaiproject/access/tool/AccessServlet.java b/access-impl/impl/src/java/org/sakaiproject/access/tool/AccessServlet.java index f6e9c7a..9746d21 100644 --- a/access-impl/impl/src/java/org/sakaiproject/access/tool/AccessServlet.java +++ b/access-impl/impl/src/java/org/sakaiproject/access/tool/AccessServlet.java @@ -1,596 +1,598 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.access.tool; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.cheftool.VmServlet; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityAccessOverloadException; import org.sakaiproject.entity.api.EntityCopyrightException; import org.sakaiproject.entity.api.EntityNotDefinedException; import org.sakaiproject.entity.api.EntityPermissionException; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.HttpAccess; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.tool.api.ActiveTool; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.tool.cover.ActiveToolManager; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.util.BaseResourceProperties; import org.sakaiproject.util.BasicAuth; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.Validator; import org.sakaiproject.util.Web; /** * <p> * Access is a servlet that provides a portal to entity access by URL for Sakai.<br /> * The servlet takes the requests and dispatches to the appropriate EntityProducer for the response.<br /> * Any error handling is done here.<br /> * If the user has not yet logged in and need to for permission, the login process is handled here, too. * </p> * * @author Sakai Software Development Team */ public class AccessServlet extends VmServlet { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(AccessServlet.class); /** Resource bundle using current language locale */ protected static ResourceLoader rb = new ResourceLoader("access"); /** stream content requests if true, read all into memory and send if false. */ protected static final boolean STREAM_CONTENT = true; /** The chunk size used when streaming (100k). */ protected static final int STREAM_BUFFER_SIZE = 102400; /** delimiter for form multiple values */ protected static final String FORM_VALUE_DELIMETER = "^"; /** set to true when init'ed. */ protected boolean m_ready = false; /** copyright path -- MUST have same value as ResourcesAction.COPYRIGHT_PATH */ protected static final String COPYRIGHT_PATH = Entity.SEPARATOR + "copyright"; /** Path used when forcing the user to accept the copyright agreement . */ protected static final String COPYRIGHT_REQUIRE = Entity.SEPARATOR + "require"; /** Path used when the user has accepted the copyright agreement . */ protected static final String COPYRIGHT_ACCEPT = Entity.SEPARATOR + "accept"; /** Ref accepted, request parameter for COPYRIGHT_ACCEPT request. */ protected static final String COPYRIGHT_ACCEPT_REF = "ref"; /** Return URL, request parameter for COPYRIGHT_ACCEPT request. */ protected static final String COPYRIGHT_ACCEPT_URL = "url"; /** Session attribute holding copyright-accepted references (a collection of Strings). */ protected static final String COPYRIGHT_ACCEPTED_REFS_ATTR = "Access.Copyright.Accepted"; protected BasicAuth basicAuth = null; /** init thread - so we don't wait in the actual init() call */ public class AccessServletInit extends Thread { /** * construct and start the init activity */ public AccessServletInit() { m_ready = false; start(); } /** * run the init */ public void run() { m_ready = true; } } /** * initialize the AccessServlet servlet * * @param config * the servlet config parameter * @exception ServletException * in case of difficulties */ public void init(ServletConfig config) throws ServletException { super.init(config); startInit(); basicAuth = new BasicAuth(); basicAuth.init(); } /** * Start the initialization process */ public void startInit() { new AccessServletInit(); } /** * respond to an HTTP GET request * * @param req * HttpServletRequest object with the client request * @param res * HttpServletResponse object back to the client * @exception ServletException * in case of difficulties * @exception IOException * in case of difficulties */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // process any login that might be present basicAuth.doLogin(req); // catch the login helper requests String option = req.getPathInfo(); String[] parts = option.split("/"); if ((parts.length == 2) && ((parts[1].equals("login")))) { doLogin(req, res, null); } else { dispatch(req, res); } } /** * respond to an HTTP POST request; only to handle the login process * * @param req * HttpServletRequest object with the client request * @param res * HttpServletResponse object back to the client * @exception ServletException * in case of difficulties * @exception IOException * in case of difficulties */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // process any login that might be present basicAuth.doLogin(req); // catch the login helper posts String option = req.getPathInfo(); String[] parts = option.split("/"); if ((parts.length == 2) && ((parts[1].equals("login")))) { doLogin(req, res, null); } else { sendError(res, HttpServletResponse.SC_NOT_FOUND); } } /** * handle get and post communication from the user * * @param req * HttpServletRequest object with the client request * @param res * HttpServletResponse object back to the client */ public void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException { ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS); // get the path info String path = params.getPath(); if (path == null) path = ""; if (!m_ready) { sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // send the sample copyright screen if (COPYRIGHT_PATH.equals(path)) { respondCopyrightAlertDemo(req, res); return; } // send the real copyright screen for some entity (encoded in the request parameter) if (COPYRIGHT_REQUIRE.equals(path)) { String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF); String returnPath = req.getParameter(COPYRIGHT_ACCEPT_URL); Reference aRef = EntityManager.newReference(acceptedRef); // get the properties - but use a security advisor to avoid needing end-user permission to the resource SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); ResourceProperties props = aRef.getProperties(); SecurityService.popAdvisor(); // send the copyright agreement interface if (props == null) { sendError(res, HttpServletResponse.SC_NOT_FOUND); } setVmReference("validator", new Validator(), req); setVmReference("props", props, req); setVmReference("tlang", rb, req); String acceptPath = Web.returnUrl(req, COPYRIGHT_ACCEPT + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(aRef.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(returnPath)); setVmReference("accept", acceptPath, req); res.setContentType("text/html; charset=UTF-8"); includeVm("vm/access/copyrightAlert.vm", req, res); return; } // make sure we have a collection for accepted copyright agreements Collection accepted = (Collection) SessionManager.getCurrentSession().getAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR); if (accepted == null) { accepted = new Vector(); SessionManager.getCurrentSession().setAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR, accepted); } // for accepted copyright, mark it and redirect to the entity's access URL if (COPYRIGHT_ACCEPT.equals(path)) { String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF); Reference aRef = EntityManager.newReference(acceptedRef); // save this with the session's other accepted refs accepted.add(aRef.getReference()); // redirect to the original URL String returnPath = Validator.escapeUrl( req.getParameter(COPYRIGHT_ACCEPT_URL) ); try { res.sendRedirect(Web.returnUrl(req, returnPath)); } catch (IOException e) { sendError(res, HttpServletResponse.SC_NOT_FOUND); } return; } // pre-process the path String origPath = path; path = preProcessPath(path, req); // what is being requested? Reference ref = EntityManager.newReference(path); // get the incoming information AccessServletInfo info = newInfo(req); // let the entity producer handle it try { // make sure we have a valid reference with an entity producer we can talk to EntityProducer service = ref.getEntityProducer(); if (service == null) throw new EntityNotDefinedException(ref.getReference()); // get the producer's HttpAccess helper, it might not support one HttpAccess access = service.getHttpAccess(); if (access == null) throw new EntityNotDefinedException(ref.getReference()); // let the helper do the work access.handleAccess(req, res, ref, accepted); } catch (EntityNotDefinedException e) { // the request was not valid in some way + M_log.error("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_NOT_FOUND); return; } catch (EntityPermissionException e) { // the end user does not have permission - offer a login if there is no user id yet established // if not permitted, and the user is the anon user, let them login if (SessionManager.getCurrentSessionUserId() == null) { try { doLogin(req, res, origPath); } catch ( IOException ioex ) {} return; } // otherwise reject the request + M_log.error("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_FORBIDDEN); } catch (EntityAccessOverloadException e) { M_log.info("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (EntityCopyrightException e) { // redirect to the copyright agreement interface for this entity try { // TODO: send back using a form of the request URL, encoding the real reference, and the requested reference // Note: refs / requests with servlet parameters (?x=y...) are NOT supported -ggolden String redirPath = COPYRIGHT_REQUIRE + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(e.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(req.getPathInfo()); res.sendRedirect(Web.returnUrl(req, redirPath)); } catch (IOException ee) { } return; } catch (Throwable e) { M_log.warn("dispatch(): exception: ", e); sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // log if (M_log.isDebugEnabled()) M_log.debug("from:" + req.getRemoteAddr() + " path:" + params.getPath() + " options: " + info.optionsString() + " time: " + info.getElapsedTime()); } } /** * Make any changes needed to the path before final "ref" processing. * * @param path * The path from the request. * @req The request object. * @return The path to use to make the Reference for further processing. */ protected String preProcessPath(String path, HttpServletRequest req) { return path; } /** * Make the Sample Copyright Alert response. * * @param req * HttpServletRequest object with the client request. * @param res * HttpServletResponse object back to the client. */ protected void respondCopyrightAlertDemo(HttpServletRequest req, HttpServletResponse res) throws ServletException { // the context wraps our real vm attribute set ResourceProperties props = new BaseResourceProperties(); setVmReference("props", props, req); setVmReference("validator", new Validator(), req); setVmReference("sample", Boolean.TRUE.toString(), req); setVmReference("tlang", rb, req); res.setContentType("text/html; charset=UTF-8"); includeVm("vm/access/copyrightAlert.vm", req, res); } /** * Make a redirect to the login url. * * @param req * HttpServletRequest object with the client request. * @param res * HttpServletResponse object back to the client. * @param path * The current request path, set ONLY if we want this to be where to redirect the user after successfull login * @throws IOException */ protected void doLogin(HttpServletRequest req, HttpServletResponse res, String path) throws ToolException, IOException { // if basic auth is valid do that if ( basicAuth.doAuth(req,res) ) { //System.err.println("BASIC Auth Request Sent to the Browser "); return; } // get the Sakai session Session session = SessionManager.getCurrentSession(); // set the return path for after login if needed (Note: in session, not tool session, special for Login helper) if (path != null) { // where to go after session.setAttribute(Tool.HELPER_DONE_URL, Web.returnUrl(req, Validator.escapeUrl(path))); } // check that we have a return path set; might have been done earlier if (session.getAttribute(Tool.HELPER_DONE_URL) == null) { M_log.warn("doLogin - proceeding with null HELPER_DONE_URL"); } // map the request to the helper, leaving the path after ".../options" for the helper ActiveTool tool = ActiveToolManager.getActiveTool("sakai.login"); String context = req.getContextPath() + req.getServletPath() + "/login"; tool.help(req, res, context, "/login"); } /** create the info */ protected AccessServletInfo newInfo(HttpServletRequest req) { return new AccessServletInfo(req); } protected void sendError(HttpServletResponse res, int code) { try { res.sendError(code); } catch (Throwable t) { M_log.warn("sendError: " + t); } } public class AccessServletInfo { // elapsed time start protected long m_startTime = System.currentTimeMillis(); public long getStartTime() { return m_startTime; } public long getElapsedTime() { return System.currentTimeMillis() - m_startTime; } // all properties from the request protected Properties m_options = null; /** construct from the req */ public AccessServletInfo(HttpServletRequest req) { m_options = new Properties(); String type = req.getContentType(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String[] values = req.getParameterValues(key); if (values.length == 1) { m_options.put(key, values[0]); } else { StringBuilder buf = new StringBuilder(); for (int i = 0; i < values.length; i++) { buf.append(values[i] + FORM_VALUE_DELIMETER); } m_options.put(key, buf.toString()); } } } /** return the m_options as a string - obscure any "password" fields */ public String optionsString() { StringBuilder buf = new StringBuilder(1024); Enumeration e = m_options.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); Object o = m_options.getProperty(key); if (o instanceof String) { buf.append(key); buf.append("="); if (key.equals("password")) { buf.append("*****"); } else { buf.append(o.toString()); } buf.append("&"); } } return buf.toString(); } } /** * A simple SecurityAdviser that can be used to override permissions on one reference string for one user for one function. */ public class SimpleSecurityAdvisor implements SecurityAdvisor { protected String m_userId; protected String m_function; protected String m_reference; public SimpleSecurityAdvisor(String userId, String function, String reference) { m_userId = userId; m_function = function; m_reference = reference; } public SecurityAdvice isAllowed(String userId, String function, String reference) { SecurityAdvice rv = SecurityAdvice.PASS; if (m_userId.equals(userId) && m_function.equals(function) && m_reference.equals(reference)) { rv = SecurityAdvice.ALLOWED; } return rv; } } }
false
true
public void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException { ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS); // get the path info String path = params.getPath(); if (path == null) path = ""; if (!m_ready) { sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // send the sample copyright screen if (COPYRIGHT_PATH.equals(path)) { respondCopyrightAlertDemo(req, res); return; } // send the real copyright screen for some entity (encoded in the request parameter) if (COPYRIGHT_REQUIRE.equals(path)) { String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF); String returnPath = req.getParameter(COPYRIGHT_ACCEPT_URL); Reference aRef = EntityManager.newReference(acceptedRef); // get the properties - but use a security advisor to avoid needing end-user permission to the resource SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); ResourceProperties props = aRef.getProperties(); SecurityService.popAdvisor(); // send the copyright agreement interface if (props == null) { sendError(res, HttpServletResponse.SC_NOT_FOUND); } setVmReference("validator", new Validator(), req); setVmReference("props", props, req); setVmReference("tlang", rb, req); String acceptPath = Web.returnUrl(req, COPYRIGHT_ACCEPT + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(aRef.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(returnPath)); setVmReference("accept", acceptPath, req); res.setContentType("text/html; charset=UTF-8"); includeVm("vm/access/copyrightAlert.vm", req, res); return; } // make sure we have a collection for accepted copyright agreements Collection accepted = (Collection) SessionManager.getCurrentSession().getAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR); if (accepted == null) { accepted = new Vector(); SessionManager.getCurrentSession().setAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR, accepted); } // for accepted copyright, mark it and redirect to the entity's access URL if (COPYRIGHT_ACCEPT.equals(path)) { String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF); Reference aRef = EntityManager.newReference(acceptedRef); // save this with the session's other accepted refs accepted.add(aRef.getReference()); // redirect to the original URL String returnPath = Validator.escapeUrl( req.getParameter(COPYRIGHT_ACCEPT_URL) ); try { res.sendRedirect(Web.returnUrl(req, returnPath)); } catch (IOException e) { sendError(res, HttpServletResponse.SC_NOT_FOUND); } return; } // pre-process the path String origPath = path; path = preProcessPath(path, req); // what is being requested? Reference ref = EntityManager.newReference(path); // get the incoming information AccessServletInfo info = newInfo(req); // let the entity producer handle it try { // make sure we have a valid reference with an entity producer we can talk to EntityProducer service = ref.getEntityProducer(); if (service == null) throw new EntityNotDefinedException(ref.getReference()); // get the producer's HttpAccess helper, it might not support one HttpAccess access = service.getHttpAccess(); if (access == null) throw new EntityNotDefinedException(ref.getReference()); // let the helper do the work access.handleAccess(req, res, ref, accepted); } catch (EntityNotDefinedException e) { // the request was not valid in some way sendError(res, HttpServletResponse.SC_NOT_FOUND); return; } catch (EntityPermissionException e) { // the end user does not have permission - offer a login if there is no user id yet established // if not permitted, and the user is the anon user, let them login if (SessionManager.getCurrentSessionUserId() == null) { try { doLogin(req, res, origPath); } catch ( IOException ioex ) {} return; } // otherwise reject the request sendError(res, HttpServletResponse.SC_FORBIDDEN); } catch (EntityAccessOverloadException e) { M_log.info("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (EntityCopyrightException e) { // redirect to the copyright agreement interface for this entity try { // TODO: send back using a form of the request URL, encoding the real reference, and the requested reference // Note: refs / requests with servlet parameters (?x=y...) are NOT supported -ggolden String redirPath = COPYRIGHT_REQUIRE + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(e.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(req.getPathInfo()); res.sendRedirect(Web.returnUrl(req, redirPath)); } catch (IOException ee) { } return; } catch (Throwable e) { M_log.warn("dispatch(): exception: ", e); sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // log if (M_log.isDebugEnabled()) M_log.debug("from:" + req.getRemoteAddr() + " path:" + params.getPath() + " options: " + info.optionsString() + " time: " + info.getElapsedTime()); } }
public void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException { ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS); // get the path info String path = params.getPath(); if (path == null) path = ""; if (!m_ready) { sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // send the sample copyright screen if (COPYRIGHT_PATH.equals(path)) { respondCopyrightAlertDemo(req, res); return; } // send the real copyright screen for some entity (encoded in the request parameter) if (COPYRIGHT_REQUIRE.equals(path)) { String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF); String returnPath = req.getParameter(COPYRIGHT_ACCEPT_URL); Reference aRef = EntityManager.newReference(acceptedRef); // get the properties - but use a security advisor to avoid needing end-user permission to the resource SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); ResourceProperties props = aRef.getProperties(); SecurityService.popAdvisor(); // send the copyright agreement interface if (props == null) { sendError(res, HttpServletResponse.SC_NOT_FOUND); } setVmReference("validator", new Validator(), req); setVmReference("props", props, req); setVmReference("tlang", rb, req); String acceptPath = Web.returnUrl(req, COPYRIGHT_ACCEPT + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(aRef.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(returnPath)); setVmReference("accept", acceptPath, req); res.setContentType("text/html; charset=UTF-8"); includeVm("vm/access/copyrightAlert.vm", req, res); return; } // make sure we have a collection for accepted copyright agreements Collection accepted = (Collection) SessionManager.getCurrentSession().getAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR); if (accepted == null) { accepted = new Vector(); SessionManager.getCurrentSession().setAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR, accepted); } // for accepted copyright, mark it and redirect to the entity's access URL if (COPYRIGHT_ACCEPT.equals(path)) { String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF); Reference aRef = EntityManager.newReference(acceptedRef); // save this with the session's other accepted refs accepted.add(aRef.getReference()); // redirect to the original URL String returnPath = Validator.escapeUrl( req.getParameter(COPYRIGHT_ACCEPT_URL) ); try { res.sendRedirect(Web.returnUrl(req, returnPath)); } catch (IOException e) { sendError(res, HttpServletResponse.SC_NOT_FOUND); } return; } // pre-process the path String origPath = path; path = preProcessPath(path, req); // what is being requested? Reference ref = EntityManager.newReference(path); // get the incoming information AccessServletInfo info = newInfo(req); // let the entity producer handle it try { // make sure we have a valid reference with an entity producer we can talk to EntityProducer service = ref.getEntityProducer(); if (service == null) throw new EntityNotDefinedException(ref.getReference()); // get the producer's HttpAccess helper, it might not support one HttpAccess access = service.getHttpAccess(); if (access == null) throw new EntityNotDefinedException(ref.getReference()); // let the helper do the work access.handleAccess(req, res, ref, accepted); } catch (EntityNotDefinedException e) { // the request was not valid in some way M_log.error("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_NOT_FOUND); return; } catch (EntityPermissionException e) { // the end user does not have permission - offer a login if there is no user id yet established // if not permitted, and the user is the anon user, let them login if (SessionManager.getCurrentSessionUserId() == null) { try { doLogin(req, res, origPath); } catch ( IOException ioex ) {} return; } // otherwise reject the request M_log.error("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_FORBIDDEN); } catch (EntityAccessOverloadException e) { M_log.info("dispatch(): ref: " + ref.getReference() + e); sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (EntityCopyrightException e) { // redirect to the copyright agreement interface for this entity try { // TODO: send back using a form of the request URL, encoding the real reference, and the requested reference // Note: refs / requests with servlet parameters (?x=y...) are NOT supported -ggolden String redirPath = COPYRIGHT_REQUIRE + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(e.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(req.getPathInfo()); res.sendRedirect(Web.returnUrl(req, redirPath)); } catch (IOException ee) { } return; } catch (Throwable e) { M_log.warn("dispatch(): exception: ", e); sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // log if (M_log.isDebugEnabled()) M_log.debug("from:" + req.getRemoteAddr() + " path:" + params.getPath() + " options: " + info.optionsString() + " time: " + info.getElapsedTime()); } }
diff --git a/backends/src/net/sf/orcc/backends/c/quasistatic/scheduler/unrollers/ConfigurationAnalyzer.java b/backends/src/net/sf/orcc/backends/c/quasistatic/scheduler/unrollers/ConfigurationAnalyzer.java index 7433f056e..1c44ecb98 100644 --- a/backends/src/net/sf/orcc/backends/c/quasistatic/scheduler/unrollers/ConfigurationAnalyzer.java +++ b/backends/src/net/sf/orcc/backends/c/quasistatic/scheduler/unrollers/ConfigurationAnalyzer.java @@ -1,501 +1,501 @@ /* * Copyright (c) 2009, IETR/INSA of Rennes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the IETR/INSA of Rennes nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.backends.c.quasistatic.scheduler.unrollers; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jp.ac.kobe_u.cs.cream.DefaultSolver; import jp.ac.kobe_u.cs.cream.IntVariable; import jp.ac.kobe_u.cs.cream.Network; import jp.ac.kobe_u.cs.cream.Solution; import net.sf.orcc.OrccRuntimeException; import net.sf.orcc.ir.Action; import net.sf.orcc.ir.ActionScheduler; import net.sf.orcc.ir.Actor; import net.sf.orcc.ir.CFGNode; import net.sf.orcc.ir.Expression; import net.sf.orcc.ir.FSM; import net.sf.orcc.ir.Port; import net.sf.orcc.ir.Procedure; import net.sf.orcc.ir.Type; import net.sf.orcc.ir.Variable; import net.sf.orcc.ir.FSM.NextStateInfo; import net.sf.orcc.ir.expr.BinaryExpr; import net.sf.orcc.ir.expr.BinaryOp; import net.sf.orcc.ir.expr.BoolExpr; import net.sf.orcc.ir.expr.ExpressionEvaluator; import net.sf.orcc.ir.expr.ExpressionInterpreter; import net.sf.orcc.ir.expr.IntExpr; import net.sf.orcc.ir.expr.ListExpr; import net.sf.orcc.ir.expr.StringExpr; import net.sf.orcc.ir.expr.UnaryExpr; import net.sf.orcc.ir.expr.VarExpr; import net.sf.orcc.ir.instructions.Assign; import net.sf.orcc.ir.instructions.Load; import net.sf.orcc.ir.instructions.Peek; import net.sf.orcc.ir.nodes.NodeVisitor; import net.sf.orcc.ir.transforms.AbstractActorTransformation; import net.sf.orcc.ir.type.IntType; import net.sf.orcc.ir.type.UintType; /** * This class defines a configuration analyzer. * * @author Matthieu Wipliez * */ public class ConfigurationAnalyzer { /** * This class defines a visitor that examines expressions that depend on a * value peeked from the configuration port. * * @author Matthieu Wipliez * */ private class ConstraintExpressionVisitor implements ExpressionInterpreter { private IntVariable constraintVariable; private Variable target; /** * Creates a new constraint expression visitor that adds constraints on * the given token variables to expressions that involve the given * target. * * @param target * target variable * @param constraintVariable * constraint variable */ public ConstraintExpressionVisitor(Variable target, IntVariable constraintVariable) { this.target = target; this.constraintVariable = constraintVariable; } /** * Adds a constraint between an integer variable and either another * integer variable or an integer value. * * @param v1 * an integer variable * @param op * a binary operator * @param o2 * an integer variable or an integer value */ private Object addConstraint(IntVariable v1, BinaryOp op, Object o2) { switch (op) { case BITAND: if (o2 instanceof IntVariable) { v1.bitand((IntVariable) o2); } else if (o2 instanceof Integer) { v1.bitand((Integer) o2); } else { break; } case EQ: if (o2 instanceof IntVariable) { v1.equals((IntVariable) o2); } else if (o2 instanceof Integer) { - v1.equals((Integer) o2); + v1.equals(((Integer) o2).intValue()); } else { break; } return v1; case GE: if (o2 instanceof IntVariable) { v1.ge((IntVariable) o2); } else if (o2 instanceof Integer) { v1.ge((Integer) o2); } else { break; } return v1; case GT: if (o2 instanceof IntVariable) { v1.gt((IntVariable) o2); } else if (o2 instanceof Integer) { v1.gt((Integer) o2); } else { break; } return v1; case LE: if (o2 instanceof IntVariable) { v1.le((IntVariable) o2); } else if (o2 instanceof Integer) { v1.le((Integer) o2); } else { break; } return v1; case LT: if (o2 instanceof IntVariable) { v1.lt((IntVariable) o2); } else if (o2 instanceof Integer) { v1.lt((Integer) o2); } else { break; } return v1; case NE: if (o2 instanceof IntVariable) { v1.notEquals((IntVariable) o2); } else if (o2 instanceof Integer) { v1.notEquals((Integer) o2); } else { break; } return v1; } return null; } @Override public Object interpret(BinaryExpr expr, Object... args) { Object o1 = expr.getE1().accept(this); Object o2 = expr.getE2().accept(this); if (o1 instanceof IntVariable) { IntVariable v1 = (IntVariable) o1; return addConstraint(v1, expr.getOp(), o2); } else { if (o2 instanceof IntVariable) { IntVariable v2 = (IntVariable) o2; return addConstraint(v2, expr.getOp() .inequalityOpChangeOrder(), o1); } else { // no variable in binary expression return null; } } } @Override public Object interpret(BoolExpr expr, Object... args) { return null; } @Override public Object interpret(IntExpr expr, Object... args) { return expr.getValue(); } @Override public Object interpret(ListExpr expr, Object... args) { return null; } @Override public Object interpret(StringExpr expr, Object... args) { return null; } @Override public Object interpret(UnaryExpr expr, Object... args) { switch (expr.getOp()) { case MINUS: Object obj = expr.getExpr().accept(this); if (obj instanceof IntVariable) { return ((IntVariable) obj).negate(); } else if (obj instanceof Integer) { return -((Integer) obj); } } return null; } @Override public Object interpret(VarExpr expr, Object... args) { Variable variable = expr.getVar().getVariable(); if (variable.equals(target)) { return constraintVariable; } else { return null; } } } /** * This class defines a visitor that examines guards that depend on a value * peeked from the configuration port. This visitor is only run if there is * a configuration port. * * @author Matthieu Wipliez * */ private class GuardVisitor extends AbstractActorTransformation { private IntVariable constraintVariable; private Network network; private Variable target; private Variable tokens; public GuardVisitor() { network = new Network(); } /** * Returns the constraint variable. * * @return the constraint variable */ public IntVariable getVariable() { return constraintVariable; } @Override public void visit(Assign assign, Object... args) { ConstraintExpressionVisitor visitor = new ConstraintExpressionVisitor( target, constraintVariable); assign.getValue().accept(visitor); } @Override public void visit(Load load, Object... args) { if (load.getSource().getVariable().equals(tokens)) { target = load.getTarget(); } } @Override public void visit(Peek peek, Object... args) { if (peek.getPort().equals(port)) { tokens = peek.getTarget(); int lo; int hi; if (port.getType().getType() == Type.INT) { IntType type = (IntType) port.getType(); Expression size = type.getSize(); ExpressionEvaluator evaluator = new ExpressionEvaluator(); int num = evaluator.evaluateAsInteger(size); lo = -(1 << (num - 1)); hi = (1 << (num - 1)) - 1; } else if (port.getType().getType() == Type.UINT) { UintType type = (UintType) port.getType(); Expression size = type.getSize(); ExpressionEvaluator evaluator = new ExpressionEvaluator(); int num = evaluator.evaluateAsInteger(size); lo = 0; hi = 1 << num - 1; } else { throw new OrccRuntimeException("integer ports only"); } constraintVariable = new IntVariable(network, lo, hi, port .getName()); } } } /** * This class defines a visitor that finds a set of ports peeked. * * @author Matthieu Wipliez * */ private class PeekVisitor extends AbstractActorTransformation { private Set<Port> candidates; /** * Creates a new peek visitor. */ public PeekVisitor() { candidates = new HashSet<Port>(); } /** * Returns the set of candidate ports. * * @return the set of candidate ports */ public Set<Port> getCandidates() { return candidates; } @Override public void visit(Peek peek, Object... args) { candidates.add(peek.getPort()); } } private Actor actor; private FSM fsm; private String initialState; private Port port; private Map<Action, IntVariable> values; /** * Creates a new configuration analyzer for the given actor * * @param actor * an actor */ public ConfigurationAnalyzer(Actor actor) { this.actor = actor; values = new HashMap<Action, IntVariable>(); } /** * Analyze the actor given at construction time */ public void analyze() { ActionScheduler sched = actor.getActionScheduler(); if (sched.hasFsm()) { fsm = sched.getFsm(); initialState = fsm.getInitialState().getName(); findConfigurationPort(); if (port != null) { findConstraints(); } } } /** * Finds the configuration port of this FSM is there is one. */ private void findConfigurationPort() { // visits the scheduler of each action departing from the initial state List<Set<Port>> ports = new ArrayList<Set<Port>>(); for (NextStateInfo info : fsm.getTransitions(initialState)) { PeekVisitor visitor = new PeekVisitor(); visitAction(info, visitor); ports.add(visitor.getCandidates()); } // get the intersection of all ports Set<Port> candidates = new HashSet<Port>(); // add all ports peeked for (Set<Port> set : ports) { candidates.addAll(set); } // get the intersection for (Set<Port> set : ports) { if (!set.isEmpty()) { candidates.retainAll(set); } } // set the port if there is only one if (candidates.size() == 1) { port = candidates.iterator().next(); } } private void findConstraints() { // visits the scheduler of each action departing from the initial state for (NextStateInfo info : fsm.getTransitions(initialState)) { GuardVisitor visitor = new GuardVisitor(); visitAction(info, visitor); if (visitor.getVariable() == null) { System.out.println("no constraint on " + port); } else { values.put(info.getAction(), visitor.getVariable()); } } } /** * Returns the configuration port. * * @return the configuration port */ public Port getConfigurationPort() { return port; } /** * Get a value that, read on the configuration port, would enable the given * action to fire. * * @param action * an action * @return an integer value */ public int getConfigurationValue(Action action) { IntVariable variable = values.get(action); if (variable != null) { DefaultSolver solver = new DefaultSolver(variable.getNetwork()); Solution solution = solver.findFirst(); if (solution != null) { int value = solution.getIntValue(variable); System.out.println("solution found for " + action + ", returning " + value); return value; } } System.out.println("returning 0 for " + action); return 0; } /** * Visits the action stored in the given next state information with the * given visitor. * * @param info * information about the next state * @param visitor * a node visitor */ private void visitAction(NextStateInfo info, NodeVisitor visitor) { Action action = info.getAction(); Procedure scheduler = action.getScheduler(); for (CFGNode node : scheduler.getNodes()) { node.accept(visitor); } } }
true
true
private Object addConstraint(IntVariable v1, BinaryOp op, Object o2) { switch (op) { case BITAND: if (o2 instanceof IntVariable) { v1.bitand((IntVariable) o2); } else if (o2 instanceof Integer) { v1.bitand((Integer) o2); } else { break; } case EQ: if (o2 instanceof IntVariable) { v1.equals((IntVariable) o2); } else if (o2 instanceof Integer) { v1.equals((Integer) o2); } else { break; } return v1; case GE: if (o2 instanceof IntVariable) { v1.ge((IntVariable) o2); } else if (o2 instanceof Integer) { v1.ge((Integer) o2); } else { break; } return v1; case GT: if (o2 instanceof IntVariable) { v1.gt((IntVariable) o2); } else if (o2 instanceof Integer) { v1.gt((Integer) o2); } else { break; } return v1; case LE: if (o2 instanceof IntVariable) { v1.le((IntVariable) o2); } else if (o2 instanceof Integer) { v1.le((Integer) o2); } else { break; } return v1; case LT: if (o2 instanceof IntVariable) { v1.lt((IntVariable) o2); } else if (o2 instanceof Integer) { v1.lt((Integer) o2); } else { break; } return v1; case NE: if (o2 instanceof IntVariable) { v1.notEquals((IntVariable) o2); } else if (o2 instanceof Integer) { v1.notEquals((Integer) o2); } else { break; } return v1; } return null; }
private Object addConstraint(IntVariable v1, BinaryOp op, Object o2) { switch (op) { case BITAND: if (o2 instanceof IntVariable) { v1.bitand((IntVariable) o2); } else if (o2 instanceof Integer) { v1.bitand((Integer) o2); } else { break; } case EQ: if (o2 instanceof IntVariable) { v1.equals((IntVariable) o2); } else if (o2 instanceof Integer) { v1.equals(((Integer) o2).intValue()); } else { break; } return v1; case GE: if (o2 instanceof IntVariable) { v1.ge((IntVariable) o2); } else if (o2 instanceof Integer) { v1.ge((Integer) o2); } else { break; } return v1; case GT: if (o2 instanceof IntVariable) { v1.gt((IntVariable) o2); } else if (o2 instanceof Integer) { v1.gt((Integer) o2); } else { break; } return v1; case LE: if (o2 instanceof IntVariable) { v1.le((IntVariable) o2); } else if (o2 instanceof Integer) { v1.le((Integer) o2); } else { break; } return v1; case LT: if (o2 instanceof IntVariable) { v1.lt((IntVariable) o2); } else if (o2 instanceof Integer) { v1.lt((Integer) o2); } else { break; } return v1; case NE: if (o2 instanceof IntVariable) { v1.notEquals((IntVariable) o2); } else if (o2 instanceof Integer) { v1.notEquals((Integer) o2); } else { break; } return v1; } return null; }
diff --git a/src/java/com/idega/content/presentation/WebDAVList.java b/src/java/com/idega/content/presentation/WebDAVList.java index db1f3f0d..46d6faf0 100644 --- a/src/java/com/idega/content/presentation/WebDAVList.java +++ b/src/java/com/idega/content/presentation/WebDAVList.java @@ -1,149 +1,149 @@ package com.idega.content.presentation; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import org.apache.myfaces.custom.savestate.UISaveState; import com.idega.presentation.IWBaseComponent; import com.idega.webface.WFList; import com.idega.webface.WFUtil; /** * @author gimmi * * Component that lists up a content of a WebDAV folder */ public class WebDAVList extends IWBaseComponent { public final static String WEB_DAV_LIST_BEAN_ID = "WebDAVListBean"; private String startFolder = null; private String rootFolder = null; private String iconTheme = null; private boolean showFolders = true; private boolean showPublicFolder = true; private boolean showDropboxFolder = true; private Collection columnsToHide = null; private boolean useVersionControl = true; private String onFileClickEvent = null; public WebDAVList() { } protected void initializeComponent(FacesContext context) { WebDAVListManagedBean bean = getWebDAVListManagedBean(); if (this.startFolder != null) { bean.setStartFolder(this.startFolder); } else { bean.setStartFolder(""); } if (this.rootFolder != null) { bean.setRootFolder(this.rootFolder); } else { bean.setRootFolder(""); } if (this.iconTheme != null) { bean.setIconTheme(this.iconTheme); } else { bean.setIconTheme(""); } if (this.onFileClickEvent != null) { bean.setOnFileClickEvent(this.onFileClickEvent); } else { bean.setOnFileClickEvent(""); } bean.setShowFolders(new Boolean(this.showFolders)); bean.setShowPublicFolder(new Boolean(this.showPublicFolder)); bean.setShowDropboxFolder(new Boolean(this.showDropboxFolder)); if (this.columnsToHide != null) { bean.addColumnsToHide(this.columnsToHide); } else { //bean.setColumnsToHide(new Vector()); } bean.setUseVersionControl(new Boolean(this.useVersionControl)); //WFContainer wrapper = new WFContainer(); //wrapper.setStyleClass("scrollWrapper"); this.setId(this.getId()); WFList list = new WFList(WEB_DAV_LIST_BEAN_ID, 0, 0); /*list.setListStyleClass(list.getListStyleClass()+" scrollContainer"); list.setId("scrollContainer"); list.setStyleClass("scrollTable");*/ list.setBodyScrollable(true); list.setId(this.getId()+"_l"); //wrapper.getChildren().add(list); add(list); //to make this object request safe, extension from myfaces //ask Tryggvi UISaveState beanSaveState = new UISaveState(); - ValueBinding binding = WFUtil.createValueBinding("#{"+WEB_DAV_LIST_BEAN_ID+"}"); + ValueBinding binding = WFUtil.createValueBinding("#{"+WEB_DAV_LIST_BEAN_ID+".dataModel}"); beanSaveState.setId("WebDavListBeanSaveState"); - beanSaveState.setValueBinding("value",binding); + beanSaveState.setValueBinding("value", binding); add(beanSaveState); } protected WebDAVListManagedBean getWebDAVListManagedBean(){ return (WebDAVListManagedBean) WFUtil.getBeanInstance(WEB_DAV_LIST_BEAN_ID); } public void setStartFolder(String start) { this.startFolder = start; } public void setRootFolder(String root) { this.rootFolder = root; } public void setIconTheme(String theme) { this.iconTheme = theme; } public void setShowFolders(boolean showFolders) { this.showFolders = showFolders; } public void setShowPublicFolder(boolean showPublicFolder){ this.showPublicFolder = showPublicFolder; } public void setShowDropboxFolder(boolean showDropboxFolder){ this.showDropboxFolder = showDropboxFolder; } public void setColumnsToHide(Collection columns) { this.columnsToHide = columns; } public void setUseVersionControl(boolean useVersionControl) { this.useVersionControl = useVersionControl; } public void setOnFileClickEvent(String event) { this.onFileClickEvent = event; } public void encodeChildren(FacesContext context) throws IOException{ super.encodeChildren(context); for (Iterator iter = getChildren().iterator(); iter.hasNext();) { UIComponent child = (UIComponent) iter.next(); renderChild(context,child); } } public boolean getRendersChildren() { return true; } }
false
true
protected void initializeComponent(FacesContext context) { WebDAVListManagedBean bean = getWebDAVListManagedBean(); if (this.startFolder != null) { bean.setStartFolder(this.startFolder); } else { bean.setStartFolder(""); } if (this.rootFolder != null) { bean.setRootFolder(this.rootFolder); } else { bean.setRootFolder(""); } if (this.iconTheme != null) { bean.setIconTheme(this.iconTheme); } else { bean.setIconTheme(""); } if (this.onFileClickEvent != null) { bean.setOnFileClickEvent(this.onFileClickEvent); } else { bean.setOnFileClickEvent(""); } bean.setShowFolders(new Boolean(this.showFolders)); bean.setShowPublicFolder(new Boolean(this.showPublicFolder)); bean.setShowDropboxFolder(new Boolean(this.showDropboxFolder)); if (this.columnsToHide != null) { bean.addColumnsToHide(this.columnsToHide); } else { //bean.setColumnsToHide(new Vector()); } bean.setUseVersionControl(new Boolean(this.useVersionControl)); //WFContainer wrapper = new WFContainer(); //wrapper.setStyleClass("scrollWrapper"); this.setId(this.getId()); WFList list = new WFList(WEB_DAV_LIST_BEAN_ID, 0, 0); /*list.setListStyleClass(list.getListStyleClass()+" scrollContainer"); list.setId("scrollContainer"); list.setStyleClass("scrollTable");*/ list.setBodyScrollable(true); list.setId(this.getId()+"_l"); //wrapper.getChildren().add(list); add(list); //to make this object request safe, extension from myfaces //ask Tryggvi UISaveState beanSaveState = new UISaveState(); ValueBinding binding = WFUtil.createValueBinding("#{"+WEB_DAV_LIST_BEAN_ID+"}"); beanSaveState.setId("WebDavListBeanSaveState"); beanSaveState.setValueBinding("value",binding); add(beanSaveState); }
protected void initializeComponent(FacesContext context) { WebDAVListManagedBean bean = getWebDAVListManagedBean(); if (this.startFolder != null) { bean.setStartFolder(this.startFolder); } else { bean.setStartFolder(""); } if (this.rootFolder != null) { bean.setRootFolder(this.rootFolder); } else { bean.setRootFolder(""); } if (this.iconTheme != null) { bean.setIconTheme(this.iconTheme); } else { bean.setIconTheme(""); } if (this.onFileClickEvent != null) { bean.setOnFileClickEvent(this.onFileClickEvent); } else { bean.setOnFileClickEvent(""); } bean.setShowFolders(new Boolean(this.showFolders)); bean.setShowPublicFolder(new Boolean(this.showPublicFolder)); bean.setShowDropboxFolder(new Boolean(this.showDropboxFolder)); if (this.columnsToHide != null) { bean.addColumnsToHide(this.columnsToHide); } else { //bean.setColumnsToHide(new Vector()); } bean.setUseVersionControl(new Boolean(this.useVersionControl)); //WFContainer wrapper = new WFContainer(); //wrapper.setStyleClass("scrollWrapper"); this.setId(this.getId()); WFList list = new WFList(WEB_DAV_LIST_BEAN_ID, 0, 0); /*list.setListStyleClass(list.getListStyleClass()+" scrollContainer"); list.setId("scrollContainer"); list.setStyleClass("scrollTable");*/ list.setBodyScrollable(true); list.setId(this.getId()+"_l"); //wrapper.getChildren().add(list); add(list); //to make this object request safe, extension from myfaces //ask Tryggvi UISaveState beanSaveState = new UISaveState(); ValueBinding binding = WFUtil.createValueBinding("#{"+WEB_DAV_LIST_BEAN_ID+".dataModel}"); beanSaveState.setId("WebDavListBeanSaveState"); beanSaveState.setValueBinding("value", binding); add(beanSaveState); }
diff --git a/plugin/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java b/plugin/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java index 2618c4d..acb0535 100644 --- a/plugin/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java +++ b/plugin/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java @@ -1,234 +1,234 @@ /* * The MIT License * * Copyright (c) 2009, NDS Group Ltd., James Nord * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jvnet.hudson.plugins.m2release; import hudson.maven.MavenModule; import hudson.maven.MavenModuleSet; import hudson.model.Action; import hudson.model.Hudson; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import org.jvnet.hudson.plugins.m2release.M2ReleaseBuildWrapper.DescriptorImpl; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * The action appears as the link in the side bar that users will click on in order to start the release * process. * * @author James Nord * @version 0.3 */ public class M2ReleaseAction implements Action { private MavenModuleSet project; private String versioningMode; private boolean selectCustomScmCommentPrefix; private boolean selectAppendHudsonUsername; public M2ReleaseAction(MavenModuleSet project, String versioningMode, boolean selectCustomScmCommentPrefix, boolean selectAppendHudsonUsername) { this.project = project; this.versioningMode = versioningMode; this.selectCustomScmCommentPrefix = selectCustomScmCommentPrefix; this.selectAppendHudsonUsername = selectAppendHudsonUsername; } public String getDisplayName() { return Messages.ReleaseAction_perform_release_name(); } public String getIconFileName() { if (M2ReleaseBuildWrapper.hasReleasePermission(project)) { return "installer.gif"; //$NON-NLS-1$ } // by returning null the link will not be shown. return null; } public String getUrlName() { return "m2release"; //$NON-NLS-1$ } public String getVersioningMode() { return versioningMode; } public void setVersioningMode(String versioningMode) { this.versioningMode = versioningMode; } public boolean isSelectCustomScmCommentPrefix() { return selectCustomScmCommentPrefix; } public void setSelectCustomScmCommentPrefix(boolean selectCustomScmCommentPrefix) { this.selectCustomScmCommentPrefix = selectCustomScmCommentPrefix; } public boolean isSelectAppendHudsonUsername() { return selectAppendHudsonUsername; } public void setSelectAppendHudsonUsername(boolean selectAppendHudsonUsername) { this.selectAppendHudsonUsername = selectAppendHudsonUsername; } public Collection<MavenModule> getModules() { return project.getModules(); } public MavenModule getRootModule() { return project.getRootModule(); } public String computeReleaseVersion(String version) { return version.replace("-SNAPSHOT", ""); //$NON-NLS-1$ //$NON-NLS-2$ } public String computeRepoDescription() { return "Release " + computeReleaseVersion(project.getRootModule().getVersion()) + " of " + project.getRootModule().getName(); } public String computeNextVersion(String version) { /// XXX would be nice to use maven to do this... /// tip: see DefaultVersionInfo.getNextVersion() in org.apache.maven.release:maven-release-manager String retVal = computeReleaseVersion(version); // get the integer after the last "." int dotIdx = retVal.lastIndexOf('.'); if (dotIdx != -1) { dotIdx++; String ver = retVal.substring(dotIdx); int intVer = Integer.parseInt(ver); intVer += 1; retVal = retVal.substring(0, dotIdx); retVal = retVal + intVer; } else { //just a major version... try { int intVer = Integer.parseInt(retVal); intVer += 1; retVal = Integer.toString(intVer); } catch (NumberFormatException nfEx) { // not a major version - just a qualifier! Logger logger = Logger.getLogger(this.getClass().getName()); logger.log(Level.WARNING, "{0} is not a number, so I can't work out the next version.", new Object[] {retVal}); retVal = "NaN"; } } return retVal + "-SNAPSHOT"; //$NON-NLS-1$ } public boolean isNexusSupportEnabled() { return project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class).getDescriptor().isNexusSupport(); } public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { M2ReleaseBuildWrapper.checkReleasePermission(project); M2ReleaseBuildWrapper m2Wrapper = project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class); // JSON collapses everything in the dynamic specifyVersions section so we need to fall back to // good old http... Map<?,?> httpParams = req.getParameterMap(); Map<String,String> versions = null; final boolean appendHudsonBuildNumber = httpParams.containsKey("appendHudsonBuildNumber"); //$NON-NLS-1$ final boolean closeNexusStage = httpParams.containsKey("closeNexusStage"); //$NON-NLS-1$ final String repoDescription = closeNexusStage ? getString("repoDescription", httpParams) : ""; //$NON-NLS-1$ final boolean specifyScmCredentials = httpParams.containsKey("specifyScmCredentials"); //$NON-NLS-1$ final String scmUsername = specifyScmCredentials ? getString("scmUsername", httpParams) : null; //$NON-NLS-1$ final String scmPassword = specifyScmCredentials ? getString("scmPassword", httpParams) : null; //$NON-NLS-1$ final boolean specifyScmCommentPrefix = httpParams.containsKey("specifyScmCommentPrefix"); //$NON-NLS-1$ final String scmCommentPrefix = specifyScmCommentPrefix ? getString("scmCommentPrefix", httpParams) : null; //$NON-NLS-1$ final boolean appendHusonUserName = specifyScmCommentPrefix && httpParams.containsKey("appendHudsonUserName"); //$NON-NLS-1$ final String versioningMode = getString("versioningMode", httpParams); if (DescriptorImpl.VERSIONING_SPECIFY_VERSIONS.equals(versioningMode)) { versions = new HashMap<String,String>(); for (Object key : httpParams.keySet()) { String keyStr = (String)key; if (keyStr.startsWith("-Dproject.")) { versions.put(keyStr, getString(keyStr, httpParams)); } } } else if (DescriptorImpl.VERSIONING_SPECIFY_VERSION.equals(versioningMode)) { versions = new HashMap<String, String>(); final String releaseVersion = getString("releaseVersion", httpParams); //$NON-NLS-1$ final String developmentVersion = getString("developmentVersion", httpParams); //$NON-NLS-1$ for(MavenModule mavenModule : getModules()) { final String name = mavenModule.getModuleName().toString(); versions.put(String.format("-Dproject.dev.%s", name), developmentVersion); //$NON-NLS-1$ versions.put(String.format("-Dproject.rel.%s", name), releaseVersion); //$NON-NLS-1$ } } // schedule release build synchronized (project) { if (project.scheduleBuild(0, new ReleaseCause())) { m2Wrapper.enableRelease(); m2Wrapper.setVersions(versions); m2Wrapper.setAppendHudsonBuildNumber(appendHudsonBuildNumber); m2Wrapper.setCloseNexusStage(closeNexusStage); m2Wrapper.setRepoDescription(repoDescription); m2Wrapper.setScmUsername(scmUsername); m2Wrapper.setScmPassword(scmPassword); m2Wrapper.setScmCommentPrefix(scmCommentPrefix); m2Wrapper.setAppendHusonUserName(appendHusonUserName); m2Wrapper.setHudsonUserName(Hudson.getAuthentication().getName()); } } // redirect to status page - resp.sendRedirect(project.getAbsoluteUrl()); + resp.sendRedirect(project.getUrl()); } /** * returns the value of the key as a String. if multiple values * have been submitted, the first one will be returned. * @param key * @param httpParams * @return */ private String getString(String key, Map<?,?> httpParams) { return (String)(((Object[])httpParams.get(key))[0]); } }
true
true
public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { M2ReleaseBuildWrapper.checkReleasePermission(project); M2ReleaseBuildWrapper m2Wrapper = project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class); // JSON collapses everything in the dynamic specifyVersions section so we need to fall back to // good old http... Map<?,?> httpParams = req.getParameterMap(); Map<String,String> versions = null; final boolean appendHudsonBuildNumber = httpParams.containsKey("appendHudsonBuildNumber"); //$NON-NLS-1$ final boolean closeNexusStage = httpParams.containsKey("closeNexusStage"); //$NON-NLS-1$ final String repoDescription = closeNexusStage ? getString("repoDescription", httpParams) : ""; //$NON-NLS-1$ final boolean specifyScmCredentials = httpParams.containsKey("specifyScmCredentials"); //$NON-NLS-1$ final String scmUsername = specifyScmCredentials ? getString("scmUsername", httpParams) : null; //$NON-NLS-1$ final String scmPassword = specifyScmCredentials ? getString("scmPassword", httpParams) : null; //$NON-NLS-1$ final boolean specifyScmCommentPrefix = httpParams.containsKey("specifyScmCommentPrefix"); //$NON-NLS-1$ final String scmCommentPrefix = specifyScmCommentPrefix ? getString("scmCommentPrefix", httpParams) : null; //$NON-NLS-1$ final boolean appendHusonUserName = specifyScmCommentPrefix && httpParams.containsKey("appendHudsonUserName"); //$NON-NLS-1$ final String versioningMode = getString("versioningMode", httpParams); if (DescriptorImpl.VERSIONING_SPECIFY_VERSIONS.equals(versioningMode)) { versions = new HashMap<String,String>(); for (Object key : httpParams.keySet()) { String keyStr = (String)key; if (keyStr.startsWith("-Dproject.")) { versions.put(keyStr, getString(keyStr, httpParams)); } } } else if (DescriptorImpl.VERSIONING_SPECIFY_VERSION.equals(versioningMode)) { versions = new HashMap<String, String>(); final String releaseVersion = getString("releaseVersion", httpParams); //$NON-NLS-1$ final String developmentVersion = getString("developmentVersion", httpParams); //$NON-NLS-1$ for(MavenModule mavenModule : getModules()) { final String name = mavenModule.getModuleName().toString(); versions.put(String.format("-Dproject.dev.%s", name), developmentVersion); //$NON-NLS-1$ versions.put(String.format("-Dproject.rel.%s", name), releaseVersion); //$NON-NLS-1$ } } // schedule release build synchronized (project) { if (project.scheduleBuild(0, new ReleaseCause())) { m2Wrapper.enableRelease(); m2Wrapper.setVersions(versions); m2Wrapper.setAppendHudsonBuildNumber(appendHudsonBuildNumber); m2Wrapper.setCloseNexusStage(closeNexusStage); m2Wrapper.setRepoDescription(repoDescription); m2Wrapper.setScmUsername(scmUsername); m2Wrapper.setScmPassword(scmPassword); m2Wrapper.setScmCommentPrefix(scmCommentPrefix); m2Wrapper.setAppendHusonUserName(appendHusonUserName); m2Wrapper.setHudsonUserName(Hudson.getAuthentication().getName()); } } // redirect to status page resp.sendRedirect(project.getAbsoluteUrl()); }
public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { M2ReleaseBuildWrapper.checkReleasePermission(project); M2ReleaseBuildWrapper m2Wrapper = project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class); // JSON collapses everything in the dynamic specifyVersions section so we need to fall back to // good old http... Map<?,?> httpParams = req.getParameterMap(); Map<String,String> versions = null; final boolean appendHudsonBuildNumber = httpParams.containsKey("appendHudsonBuildNumber"); //$NON-NLS-1$ final boolean closeNexusStage = httpParams.containsKey("closeNexusStage"); //$NON-NLS-1$ final String repoDescription = closeNexusStage ? getString("repoDescription", httpParams) : ""; //$NON-NLS-1$ final boolean specifyScmCredentials = httpParams.containsKey("specifyScmCredentials"); //$NON-NLS-1$ final String scmUsername = specifyScmCredentials ? getString("scmUsername", httpParams) : null; //$NON-NLS-1$ final String scmPassword = specifyScmCredentials ? getString("scmPassword", httpParams) : null; //$NON-NLS-1$ final boolean specifyScmCommentPrefix = httpParams.containsKey("specifyScmCommentPrefix"); //$NON-NLS-1$ final String scmCommentPrefix = specifyScmCommentPrefix ? getString("scmCommentPrefix", httpParams) : null; //$NON-NLS-1$ final boolean appendHusonUserName = specifyScmCommentPrefix && httpParams.containsKey("appendHudsonUserName"); //$NON-NLS-1$ final String versioningMode = getString("versioningMode", httpParams); if (DescriptorImpl.VERSIONING_SPECIFY_VERSIONS.equals(versioningMode)) { versions = new HashMap<String,String>(); for (Object key : httpParams.keySet()) { String keyStr = (String)key; if (keyStr.startsWith("-Dproject.")) { versions.put(keyStr, getString(keyStr, httpParams)); } } } else if (DescriptorImpl.VERSIONING_SPECIFY_VERSION.equals(versioningMode)) { versions = new HashMap<String, String>(); final String releaseVersion = getString("releaseVersion", httpParams); //$NON-NLS-1$ final String developmentVersion = getString("developmentVersion", httpParams); //$NON-NLS-1$ for(MavenModule mavenModule : getModules()) { final String name = mavenModule.getModuleName().toString(); versions.put(String.format("-Dproject.dev.%s", name), developmentVersion); //$NON-NLS-1$ versions.put(String.format("-Dproject.rel.%s", name), releaseVersion); //$NON-NLS-1$ } } // schedule release build synchronized (project) { if (project.scheduleBuild(0, new ReleaseCause())) { m2Wrapper.enableRelease(); m2Wrapper.setVersions(versions); m2Wrapper.setAppendHudsonBuildNumber(appendHudsonBuildNumber); m2Wrapper.setCloseNexusStage(closeNexusStage); m2Wrapper.setRepoDescription(repoDescription); m2Wrapper.setScmUsername(scmUsername); m2Wrapper.setScmPassword(scmPassword); m2Wrapper.setScmCommentPrefix(scmCommentPrefix); m2Wrapper.setAppendHusonUserName(appendHusonUserName); m2Wrapper.setHudsonUserName(Hudson.getAuthentication().getName()); } } // redirect to status page resp.sendRedirect(project.getUrl()); }
diff --git a/src/main/java/com/mikeprimm/bukkit/ChunkCooker/ChunkCooker.java b/src/main/java/com/mikeprimm/bukkit/ChunkCooker/ChunkCooker.java index f0c0c88..de12dd0 100644 --- a/src/main/java/com/mikeprimm/bukkit/ChunkCooker/ChunkCooker.java +++ b/src/main/java/com/mikeprimm/bukkit/ChunkCooker/ChunkCooker.java @@ -1,495 +1,496 @@ package com.mikeprimm.bukkit.ChunkCooker; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.plugin.java.JavaPlugin; public class ChunkCooker extends JavaPlugin { public Logger log; private static final int COOKER_PERIOD_INC = 5; // 1/4 second private int chunk_tick_interval = 1; // Every tick private boolean verbose = false; private ArrayList<World.Environment> worldenv; private static class UseCount { int cnt; // Number of ticking neighbors loaded boolean isTicking; } private Field chunkTickList; private Method chunkTickListPut; private Method cw_gethandle; private boolean isSpigotStyleChunkTickList; private class WorldHandler { private final World world; private final int cooker_period; // 30 seconds private final int chunks_per_period; private final boolean storm_on_empty; private final int maxLoadsPerTick; private final int minCycleTime; private final HashMap<TileFlags.TileCoord, UseCount> loadedChunks = new HashMap<TileFlags.TileCoord, UseCount>(); private final TileFlags.TileCoord[][] tickingQueue; private int tickingQueueIndex; private long cycleStart; private int endIndex; private final TileFlags chunkmap = new TileFlags(); private TileFlags.Iterator iter; private boolean stormset; WorldHandler(FileConfiguration cfg, World w) { world = w; ConfigurationSection sec = cfg.getConfigurationSection("worlds." + w.getName()); int cpp = cfg.getInt("chunks-per-period", 100); int cp = cfg.getInt("seconds-per-period", 30); boolean soe = cfg.getBoolean("storm-on-empty-world", true); int mincycle = cfg.getInt("minimum-cycle-time", 3600); if (sec != null) { cpp = sec.getInt("chunks-per-period", cpp); cp = sec.getInt("seconds-per-period", cp); soe = sec.getBoolean("storm-on-empty-world", soe); mincycle = sec.getInt("minimum-cycle-time", mincycle); } chunks_per_period = cpp; cooker_period = cp; storm_on_empty = soe; minCycleTime = mincycle; // Initialize chunk queue : enough buckets for giving chunks enough time tickingQueue = new TileFlags.TileCoord[cooker_period * 20 / COOKER_PERIOD_INC][]; tickingQueueIndex = 0; if (tickingQueue.length > 0) maxLoadsPerTick = 1 + (chunks_per_period / tickingQueue.length); else maxLoadsPerTick = 1; cycleStart = 0; log.info("World '" + w.getName() + "': chunks=" + chunks_per_period + ", period=" + cooker_period + ", storm=" + storm_on_empty + ", mintime=" + minCycleTime); } void tickCooker() { TileFlags.TileCoord tc = new TileFlags.TileCoord(); // See if any chunks due to be unloaded if (tickingQueue[tickingQueueIndex] != null) { TileFlags.TileCoord[] chunkToUnload = tickingQueue[tickingQueueIndex]; tickingQueue[tickingQueueIndex] = null; // Unload the ticking chunks for (TileFlags.TileCoord c : chunkToUnload) { UseCount cnt = loadedChunks.get(c); if (cnt != null) { cnt.isTicking = false; // Now, decrement all loaded neighbors (and self) for (tc.x = c.x - 1; tc.x <= c.x + 1; tc.x++) { for (tc.y = c.y - 1; tc.y <= c.y + 1; tc.y++) { UseCount ncnt = loadedChunks.get(tc); if (ncnt != null) { ncnt.cnt--; // Drop neighbor count if ((ncnt.cnt == 0) && (ncnt.isTicking == false)) { // No neighbors nor ticking loadedChunks.remove(tc); // Remove from set // And unload it, if its not in use if (world.isChunkInUse(tc.x, tc.y) == false) { world.unloadChunkRequest(tc.x, tc.y); } } } } } } } } + if ((iter != null) && (iter.hasNext() == false) && (tickingQueueIndex == endIndex)) { // Are we done with world? + log.info("World '" + world.getName() + "' - chunk cooking completed"); + iter = null; + endIndex = -1; + } if (iter == null) { - if (tickingQueueIndex != endIndex) { - return; - } - if (cycleStart != 0) { - log.info("World '" + world.getName() + "' - chunk cooking completed"); - } // If first cycle, or we're due for next cycle if ((cycleStart == 0) || (((System.nanoTime() - cycleStart) / 1000000000L) > minCycleTime)) { // Now, get current chunk map for world int ccnt = getChunkMap(world, chunkmap); - log.info("Starting cook pass for world '" + world.getName() + "' - " + ccnt + " existing chunks (estimated time: " + - (double)(ccnt * cooker_period * 3.0) / (double)chunks_per_period / 3600.0 + " hrs)"); + log.info(String.format("Starting cook pass for world '%s' - %d existing chunks (estimated time: %.2f hrs, minimum period: %.2f hrs)", + world.getName(), ccnt, (double)(ccnt * cooker_period * 3.0) / (double)chunks_per_period / 3600.0, + (double) minCycleTime / 3600.0)); iter = chunkmap.getIterator(); // Get iterator cycleStart = System.nanoTime(); + endIndex = -1; } else { return; } } // Now, load next N chunks (and their neighbors) ArrayList<TileFlags.TileCoord> newticking = null; int newloads = 0; while(iter.hasNext() && (loadedChunks.size() < chunks_per_period) && (newloads < maxLoadsPerTick)) { iter.next(tc); chunkmap.setFlag(tc.x, tc.y, false); int x0 = tc.x; int z0 = tc.y; // Try to load chunk, and its 8 neighbors for (tc.x = x0 - 1; tc.x <= x0 + 1; tc.x++) { for (tc.y = z0 - 1; tc.y <= z0 + 1; tc.y++) { UseCount cnt = loadedChunks.get(tc); // See if loaded if (cnt == null) { // Not yet, load it */ if (world.loadChunk(tc.x, tc.y, false)) { cnt = new UseCount(); loadedChunks.put(new TileFlags.TileCoord(tc.x, tc.y), cnt); } newloads++; } if (cnt != null) { cnt.cnt++; // Bump count if ((tc.x == x0) && (tc.y == z0)) { // If the ticking chunk, set it cnt.isTicking = true; if (newticking == null) newticking = new ArrayList<TileFlags.TileCoord>(); newticking.add(new TileFlags.TileCoord(tc.x, tc.y)); } } } } } // Add new ticking chunks to queue if (newticking != null) { tickingQueue[tickingQueueIndex] = newticking.toArray(new TileFlags.TileCoord[0]); } else { tickingQueue[tickingQueueIndex] = null; } // If iterator is exhausted, done with current world - if ((iter != null) && (iter.hasNext() == false)) { - iter = null; + if ((iter != null) && (iter.hasNext() == false) && (endIndex == -1)) { + log.info("World '" + world.getName() + "' done - finising pending chunks"); endIndex = tickingQueueIndex; } // Increment to next index tickingQueueIndex++; if (tickingQueueIndex >= tickingQueue.length) { tickingQueueIndex = 0; } if (storm_on_empty) { if (world.getPlayers().isEmpty()) { // If world is empty if (world.hasStorm() == false) { world.setStorm(true); stormset = true; if(verbose) log.info("Setting storm on empty world '" + world.getName() + "'"); } } else { if (stormset) { world.setStorm(false); stormset = false; } } } } private void putChunkTickList() { Exception xx = null; try { if ((chunkTickList != null) && (world != null)) { Object w = cw_gethandle.invoke(world); Object lst = chunkTickList.get(w); if (lst != null) { for (TileFlags.TileCoord[] ticklist : this.tickingQueue) { if (ticklist == null) continue; for (TileFlags.TileCoord tc : ticklist) { int x = tc.x; int z = tc.y; if (isSpigotStyleChunkTickList) { Long k = ((((long)x) & 0xFFFF0000L) << 16) | ((((long)x) & 0x0000FFFFL) << 0); k |= ((((long)z) & 0xFFFF0000L) << 32) | ((((long)z) & 0x0000FFFFL) << 16); chunkTickListPut.invoke(lst, k, Short.valueOf((short)-1)); } else { Long v = ((long) x << 32) + z - Integer.MIN_VALUE; chunkTickListPut.invoke(lst, v); } } } } else { log.info("No chunkTickQueue"); chunkTickList = null; } } } catch (IllegalArgumentException e) { xx = e; } catch (IllegalAccessException e) { xx = e; } catch (InvocationTargetException e) { xx = e; } if (xx != null) { log.log(Level.INFO, "Cannot send ticks", xx); chunkTickList = null; } } public void cleanup() { iter = null; loadedChunks.clear(); } } private ArrayList<WorldHandler> worlds = new ArrayList<WorldHandler>(); private void tickChunks() { for (WorldHandler wh : worlds) { wh.putChunkTickList(); } } private String getNMSPackage() { Server srv = Bukkit.getServer(); /* Get getHandle() method */ try { Method m = srv.getClass().getMethod("getHandle"); Object scm = m.invoke(srv); /* And use it to get SCM (nms object) */ return scm.getClass().getPackage().getName(); } catch (Exception x) { log.severe("Error finding net.minecraft.server packages"); return null; } } private void findChunkTickListFields() { String nms = this.getNMSPackage(); String obc = Bukkit.getServer().getClass().getPackage().getName(); boolean good = false; Exception x = null; try { Class<?> craftworld = Class.forName(obc + ".CraftWorld"); cw_gethandle = craftworld.getMethod("getHandle", new Class[0]); Class<?> cls = Class.forName(nms + ".World"); chunkTickList = cls.getDeclaredField("chunkTickList"); if (chunkTickList == null) { log.info("Cannot find chunkTickList: cannot tick chunks"); chunk_tick_interval = 0; return; } chunkTickList.setAccessible(true); // If LongHashSet, its bukkit style Class<?> ctlclass = chunkTickList.getType(); String clsname = ctlclass.getName(); if (clsname.endsWith("LongHashSet")) { chunkTickListPut = ctlclass.getMethod("add", new Class[] { long.class }); good = true; } else if (clsname.endsWith("TLongShortHashMap")) { isSpigotStyleChunkTickList = true; chunkTickListPut = ctlclass.getMethod("put", new Class[] { long.class, short.class }); good = true; } } catch (ClassNotFoundException e) { x = e; } catch (SecurityException e) { x = e; } catch (NoSuchFieldException e) { x = e; } catch (NoSuchMethodException e) { x = e; } finally { if (!good) { if (x != null) log.log(Level.INFO, "Cannot find chunkTickList: cannot tick chunks", x); else log.info("Cannot find chunkTickList: cannot tick chunks"); chunk_tick_interval = 0; chunkTickList = null; } } } public WorldHandler findWorldHandler(World w) { for (WorldHandler wh : worlds) { if (wh.world == w) { return wh; } } return null; } /* On disable, stop doing our function */ public void onDisable() { } public void onEnable() { log = this.getLogger(); log.info("ChunkCooker v" + this.getDescription().getVersion() + " loaded"); FileConfiguration cfg = getConfig(); cfg.options().copyDefaults(true); /* Load defaults, if needed */ this.saveConfig(); /* Save updates, if needed */ worldenv = new ArrayList<World.Environment>(); List<String> we = cfg.getStringList("world-env"); if (we != null) { for (String env : we) { World.Environment envval = World.Environment.valueOf(env); if (envval != null) { worldenv.add(envval); } } } else { worldenv.add(World.Environment.NORMAL); } chunk_tick_interval = cfg.getInt("chunk-tick-interval", 1); verbose = cfg.getBoolean("verbose", false); // See if we can tick chunk fields if (chunk_tick_interval > 0) { findChunkTickListFields(); } this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { for (int i = 0; i < worlds.size(); i++) { worlds.get(i).tickCooker(); } } }, COOKER_PERIOD_INC, COOKER_PERIOD_INC); if (chunk_tick_interval > 0) { this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { tickChunks(); } }, chunk_tick_interval, chunk_tick_interval); } // Initialize worlds for (World w : this.getServer().getWorlds()) { if (worldenv.contains(w.getEnvironment())) { WorldHandler wh = new WorldHandler(ChunkCooker.this.getConfig(), w); worlds.add(wh); } } // Load listener Listener pl = new Listener() { @EventHandler(priority=EventPriority.NORMAL) public void onChunkUnload(ChunkUnloadEvent evt) { if(evt.isCancelled()) return; Chunk c = evt.getChunk(); WorldHandler wh = findWorldHandler(c.getWorld()) ; if(wh != null) { TileFlags.TileCoord tc = new TileFlags.TileCoord(c.getX(), c.getZ()); if (wh.loadedChunks.containsKey(tc)) { // If loaded, cancel unload evt.setCancelled(true); } } } @EventHandler(priority=EventPriority.MONITOR) public void onWorldUnload(WorldUnloadEvent evt) { if (evt.isCancelled()) return; WorldHandler wh = findWorldHandler(evt.getWorld()); if (wh != null) { worlds.remove(wh); log.info("World '" + wh.world.getName() + "' unloaded - chunk cooking cancelled"); wh.cleanup(); } } @EventHandler(priority=EventPriority.MONITOR) public void onWorldLoad(WorldLoadEvent evt) { World w = evt.getWorld(); if (worldenv.contains(w.getEnvironment()) == false) { return; } WorldHandler wh = findWorldHandler(w); if (wh == null) { wh = new WorldHandler(ChunkCooker.this.getConfig(), w); worlds.add(wh); } } }; getServer().getPluginManager().registerEvents(pl, this); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { return false; } public int getChunkMap(World world, TileFlags map) { map.clear(); if (world == null) return -1; int cnt = 0; // Mark loaded chunks for(Chunk c : world.getLoadedChunks()) { map.setFlag(c.getX(), c.getZ(), true); cnt++; } File f = world.getWorldFolder(); File regiondir = new File(f, "region"); File[] lst = regiondir.listFiles(); if(lst != null) { byte[] hdr = new byte[4096]; for(File rf : lst) { if(!rf.getName().endsWith(".mca")) { continue; } String[] parts = rf.getName().split("\\."); if((!parts[0].equals("r")) && (parts.length != 4)) continue; RandomAccessFile rfile = null; int x = 0, z = 0; try { x = Integer.parseInt(parts[1]); z = Integer.parseInt(parts[2]); rfile = new RandomAccessFile(rf, "r"); rfile.read(hdr, 0, hdr.length); } catch (IOException iox) { Arrays.fill(hdr, (byte)0); } catch (NumberFormatException nfx) { Arrays.fill(hdr, (byte)0); } finally { if(rfile != null) { try { rfile.close(); } catch (IOException iox) {} } } for (int i = 0; i < 1024; i++) { int v = hdr[4*i] | hdr[4*i + 1] | hdr[4*i + 2] | hdr[4*i + 3]; if (v == 0) continue; int xx = (x << 5) | (i & 0x1F); int zz = (z << 5) | ((i >> 5) & 0x1F); if (!map.setFlag(xx, zz, true)) { cnt++; } } } } return cnt; } }
false
true
void tickCooker() { TileFlags.TileCoord tc = new TileFlags.TileCoord(); // See if any chunks due to be unloaded if (tickingQueue[tickingQueueIndex] != null) { TileFlags.TileCoord[] chunkToUnload = tickingQueue[tickingQueueIndex]; tickingQueue[tickingQueueIndex] = null; // Unload the ticking chunks for (TileFlags.TileCoord c : chunkToUnload) { UseCount cnt = loadedChunks.get(c); if (cnt != null) { cnt.isTicking = false; // Now, decrement all loaded neighbors (and self) for (tc.x = c.x - 1; tc.x <= c.x + 1; tc.x++) { for (tc.y = c.y - 1; tc.y <= c.y + 1; tc.y++) { UseCount ncnt = loadedChunks.get(tc); if (ncnt != null) { ncnt.cnt--; // Drop neighbor count if ((ncnt.cnt == 0) && (ncnt.isTicking == false)) { // No neighbors nor ticking loadedChunks.remove(tc); // Remove from set // And unload it, if its not in use if (world.isChunkInUse(tc.x, tc.y) == false) { world.unloadChunkRequest(tc.x, tc.y); } } } } } } } } if (iter == null) { if (tickingQueueIndex != endIndex) { return; } if (cycleStart != 0) { log.info("World '" + world.getName() + "' - chunk cooking completed"); } // If first cycle, or we're due for next cycle if ((cycleStart == 0) || (((System.nanoTime() - cycleStart) / 1000000000L) > minCycleTime)) { // Now, get current chunk map for world int ccnt = getChunkMap(world, chunkmap); log.info("Starting cook pass for world '" + world.getName() + "' - " + ccnt + " existing chunks (estimated time: " + (double)(ccnt * cooker_period * 3.0) / (double)chunks_per_period / 3600.0 + " hrs)"); iter = chunkmap.getIterator(); // Get iterator cycleStart = System.nanoTime(); } else { return; } } // Now, load next N chunks (and their neighbors) ArrayList<TileFlags.TileCoord> newticking = null; int newloads = 0; while(iter.hasNext() && (loadedChunks.size() < chunks_per_period) && (newloads < maxLoadsPerTick)) { iter.next(tc); chunkmap.setFlag(tc.x, tc.y, false); int x0 = tc.x; int z0 = tc.y; // Try to load chunk, and its 8 neighbors for (tc.x = x0 - 1; tc.x <= x0 + 1; tc.x++) { for (tc.y = z0 - 1; tc.y <= z0 + 1; tc.y++) { UseCount cnt = loadedChunks.get(tc); // See if loaded if (cnt == null) { // Not yet, load it */ if (world.loadChunk(tc.x, tc.y, false)) { cnt = new UseCount(); loadedChunks.put(new TileFlags.TileCoord(tc.x, tc.y), cnt); } newloads++; } if (cnt != null) { cnt.cnt++; // Bump count if ((tc.x == x0) && (tc.y == z0)) { // If the ticking chunk, set it cnt.isTicking = true; if (newticking == null) newticking = new ArrayList<TileFlags.TileCoord>(); newticking.add(new TileFlags.TileCoord(tc.x, tc.y)); } } } } } // Add new ticking chunks to queue if (newticking != null) { tickingQueue[tickingQueueIndex] = newticking.toArray(new TileFlags.TileCoord[0]); } else { tickingQueue[tickingQueueIndex] = null; } // If iterator is exhausted, done with current world if ((iter != null) && (iter.hasNext() == false)) { iter = null; endIndex = tickingQueueIndex; } // Increment to next index tickingQueueIndex++; if (tickingQueueIndex >= tickingQueue.length) { tickingQueueIndex = 0; } if (storm_on_empty) { if (world.getPlayers().isEmpty()) { // If world is empty if (world.hasStorm() == false) { world.setStorm(true); stormset = true; if(verbose) log.info("Setting storm on empty world '" + world.getName() + "'"); } } else { if (stormset) { world.setStorm(false); stormset = false; } } } }
void tickCooker() { TileFlags.TileCoord tc = new TileFlags.TileCoord(); // See if any chunks due to be unloaded if (tickingQueue[tickingQueueIndex] != null) { TileFlags.TileCoord[] chunkToUnload = tickingQueue[tickingQueueIndex]; tickingQueue[tickingQueueIndex] = null; // Unload the ticking chunks for (TileFlags.TileCoord c : chunkToUnload) { UseCount cnt = loadedChunks.get(c); if (cnt != null) { cnt.isTicking = false; // Now, decrement all loaded neighbors (and self) for (tc.x = c.x - 1; tc.x <= c.x + 1; tc.x++) { for (tc.y = c.y - 1; tc.y <= c.y + 1; tc.y++) { UseCount ncnt = loadedChunks.get(tc); if (ncnt != null) { ncnt.cnt--; // Drop neighbor count if ((ncnt.cnt == 0) && (ncnt.isTicking == false)) { // No neighbors nor ticking loadedChunks.remove(tc); // Remove from set // And unload it, if its not in use if (world.isChunkInUse(tc.x, tc.y) == false) { world.unloadChunkRequest(tc.x, tc.y); } } } } } } } } if ((iter != null) && (iter.hasNext() == false) && (tickingQueueIndex == endIndex)) { // Are we done with world? log.info("World '" + world.getName() + "' - chunk cooking completed"); iter = null; endIndex = -1; } if (iter == null) { // If first cycle, or we're due for next cycle if ((cycleStart == 0) || (((System.nanoTime() - cycleStart) / 1000000000L) > minCycleTime)) { // Now, get current chunk map for world int ccnt = getChunkMap(world, chunkmap); log.info(String.format("Starting cook pass for world '%s' - %d existing chunks (estimated time: %.2f hrs, minimum period: %.2f hrs)", world.getName(), ccnt, (double)(ccnt * cooker_period * 3.0) / (double)chunks_per_period / 3600.0, (double) minCycleTime / 3600.0)); iter = chunkmap.getIterator(); // Get iterator cycleStart = System.nanoTime(); endIndex = -1; } else { return; } } // Now, load next N chunks (and their neighbors) ArrayList<TileFlags.TileCoord> newticking = null; int newloads = 0; while(iter.hasNext() && (loadedChunks.size() < chunks_per_period) && (newloads < maxLoadsPerTick)) { iter.next(tc); chunkmap.setFlag(tc.x, tc.y, false); int x0 = tc.x; int z0 = tc.y; // Try to load chunk, and its 8 neighbors for (tc.x = x0 - 1; tc.x <= x0 + 1; tc.x++) { for (tc.y = z0 - 1; tc.y <= z0 + 1; tc.y++) { UseCount cnt = loadedChunks.get(tc); // See if loaded if (cnt == null) { // Not yet, load it */ if (world.loadChunk(tc.x, tc.y, false)) { cnt = new UseCount(); loadedChunks.put(new TileFlags.TileCoord(tc.x, tc.y), cnt); } newloads++; } if (cnt != null) { cnt.cnt++; // Bump count if ((tc.x == x0) && (tc.y == z0)) { // If the ticking chunk, set it cnt.isTicking = true; if (newticking == null) newticking = new ArrayList<TileFlags.TileCoord>(); newticking.add(new TileFlags.TileCoord(tc.x, tc.y)); } } } } } // Add new ticking chunks to queue if (newticking != null) { tickingQueue[tickingQueueIndex] = newticking.toArray(new TileFlags.TileCoord[0]); } else { tickingQueue[tickingQueueIndex] = null; } // If iterator is exhausted, done with current world if ((iter != null) && (iter.hasNext() == false) && (endIndex == -1)) { log.info("World '" + world.getName() + "' done - finising pending chunks"); endIndex = tickingQueueIndex; } // Increment to next index tickingQueueIndex++; if (tickingQueueIndex >= tickingQueue.length) { tickingQueueIndex = 0; } if (storm_on_empty) { if (world.getPlayers().isEmpty()) { // If world is empty if (world.hasStorm() == false) { world.setStorm(true); stormset = true; if(verbose) log.info("Setting storm on empty world '" + world.getName() + "'"); } } else { if (stormset) { world.setStorm(false); stormset = false; } } } }
diff --git a/src/impl/com/sun/ws/rest/impl/container/grizzly/GrizzlyRequestAdaptor.java b/src/impl/com/sun/ws/rest/impl/container/grizzly/GrizzlyRequestAdaptor.java index e56dab92e..7669cb694 100644 --- a/src/impl/com/sun/ws/rest/impl/container/grizzly/GrizzlyRequestAdaptor.java +++ b/src/impl/com/sun/ws/rest/impl/container/grizzly/GrizzlyRequestAdaptor.java @@ -1,132 +1,132 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License("CDDL") (the "License"). You may not use this file * except in compliance with the License. * * You can obtain a copy of the License at: * https://jersey.dev.java.net/license.txt * See the License for the specific language governing permissions and * limitations under the License. * * When distributing the Covered Code, include this CDDL Header Notice in each * file and include the License file at: * https://jersey.dev.java.net/license.txt * If applicable, add the following below this CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" */ package com.sun.ws.rest.impl.container.grizzly; import com.sun.ws.rest.spi.container.AbstractContainerRequest; import com.sun.ws.rest.impl.http.header.HttpHeaderFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Enumeration; import javax.ws.rs.core.MultivaluedMap; import org.apache.coyote.Request; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.http.MimeHeaders; /** * * @author [email protected] */ public final class GrizzlyRequestAdaptor extends AbstractContainerRequest { private final Request request; /** Creates a new instance of GrizzlyRequestAdaptor */ public GrizzlyRequestAdaptor(Request request) { super(request.method().toString(), new GrizzlyRequestInputStream(request)); this.request = request; initiateUriInfo(); copyHttpHeaders(); } private void initiateUriInfo() { /** * TODO find out exactly what the URI related methods * on org.apache.coyote.Request actually return. * If URI components are returned are they in encoded or decoded form? * If URIs are returned what components to they contain? */ try { - this.completeUri = new URI( + this.baseUri = new URI( request.scheme().toString(), null, request.serverName().toString(), request.getServerPort(), "/", null, null); this.completeUri = new URI( request.scheme().toString(), null, request.serverName().toString(), request.getServerPort(), request.requestURI().toString(), request.queryString().toString(), null); } catch (URISyntaxException ex) { ex.printStackTrace(); throw new IllegalArgumentException(ex); } } private void copyHttpHeaders() { MultivaluedMap<String, String> headers = getRequestHeaders(); MimeHeaders mh = request.getMimeHeaders(); Enumeration names = mh.names(); while (names.hasMoreElements()) { String name = (String)names.nextElement(); String value = mh.getHeader(name); headers.add(name, value); if (name.equalsIgnoreCase("cookie")) { getCookies().addAll(HttpHeaderFactory.createCookies(value)); } } } private static final class GrizzlyRequestInputStream extends InputStream { private final Request request; private final ByteChunk chunk; private ByteArrayInputStream stream; public GrizzlyRequestInputStream(Request request) { this.request = request; this.chunk = new ByteChunk(); } public int read() throws IOException { refillIfRequired(); return stream.read(); } public int read(byte[] b) throws IOException { refillIfRequired(); return stream.read(b); } private void refillIfRequired() throws IOException { if (stream==null || stream.available()==0) { //chunk.recycle(); request.doRead(chunk); if (chunk.getLength() > 0) stream = new ByteArrayInputStream(chunk.getBytes(), chunk.getStart(), chunk.getLength()); } } } }
true
true
private void initiateUriInfo() { /** * TODO find out exactly what the URI related methods * on org.apache.coyote.Request actually return. * If URI components are returned are they in encoded or decoded form? * If URIs are returned what components to they contain? */ try { this.completeUri = new URI( request.scheme().toString(), null, request.serverName().toString(), request.getServerPort(), "/", null, null); this.completeUri = new URI( request.scheme().toString(), null, request.serverName().toString(), request.getServerPort(), request.requestURI().toString(), request.queryString().toString(), null); } catch (URISyntaxException ex) { ex.printStackTrace(); throw new IllegalArgumentException(ex); } }
private void initiateUriInfo() { /** * TODO find out exactly what the URI related methods * on org.apache.coyote.Request actually return. * If URI components are returned are they in encoded or decoded form? * If URIs are returned what components to they contain? */ try { this.baseUri = new URI( request.scheme().toString(), null, request.serverName().toString(), request.getServerPort(), "/", null, null); this.completeUri = new URI( request.scheme().toString(), null, request.serverName().toString(), request.getServerPort(), request.requestURI().toString(), request.queryString().toString(), null); } catch (URISyntaxException ex) { ex.printStackTrace(); throw new IllegalArgumentException(ex); } }
diff --git a/src/main/ed/net/NIOServer.java b/src/main/ed/net/NIOServer.java index 9c3231ffd..706a2a6d2 100644 --- a/src/main/ed/net/NIOServer.java +++ b/src/main/ed/net/NIOServer.java @@ -1,205 +1,205 @@ // NIOServer.java package ed.net; import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.*; public abstract class NIOServer extends Thread { final static boolean D = Boolean.getBoolean( "DEBUG.NIO" ); public NIOServer( int port ) throws IOException { super( "NIOServer port:" + port ); _port = port; _ssChannel = ServerSocketChannel.open(); _ssChannel.configureBlocking( false ); _ssChannel.socket().bind( new InetSocketAddress( port ) ); _selector = Selector.open(); _ssChannel.register( _selector , SelectionKey.OP_ACCEPT ); setDaemon( true ); } public Selector getSelector(){ return _selector; } public void run(){ - System.out.println( "Listening on post: " + _port ); + System.out.println( "Listening on port: " + _port ); final ByteBuffer readBuf = ByteBuffer.allocateDirect(1024); final ByteBuffer writeBuf = ByteBuffer.allocateDirect(1024); while ( true ){ try { _selector.select( 10 ); } catch ( IOException ioe ){ ed.log.Logger.getLogger( "nio" ).error( "couldn't select on port : " + _port , ioe ); continue; } for ( Iterator<SelectionKey> i = _selector.selectedKeys().iterator() ; i.hasNext() ; ){ SelectionKey key = i.next(); SocketChannel sc = null; SocketHandler sh = null; try { if ( D ) System.out.println( key + " read : " + key.isReadable() + " write : " + key.isWritable() ); if ( key.isAcceptable() ){ ServerSocketChannel ssc = (ServerSocketChannel)key.channel(); sc = ssc.accept(); sc.socket().setTcpNoDelay( true ); sc.configureBlocking( false ); sh = accept( sc ); sh._key = sc.register( _selector , SelectionKey.OP_READ , sh ); if ( D ) System.out.println( sc ); i.remove(); continue; } sc = (SocketChannel)key.channel(); sh = (SocketHandler)key.attachment(); if ( sh.shouldClose() ){ if ( D ) System.out.println( "\t want to close : " + sc ); Socket temp = sc.socket(); temp.shutdownInput(); temp.shutdownOutput(); temp.close(); sc.close(); key.cancel(); continue; } if ( key.isWritable() ) sh.writeMoreIfWant(); if ( key.isReadable() ){ i.remove(); if ( D ) System.out.println( "\t" + sc ); readBuf.clear(); int read = sc.read( readBuf ); if ( D ) System.out.println( "\t\t" + read ); if ( read == -1 ){ sc.close(); continue; } if ( read == 0 ) continue; readBuf.flip(); if ( sh.gotData( readBuf ) ){ key.cancel(); continue; } } } catch ( Exception e ){ if ( sc != null ){ try { sc.close(); } catch ( Exception ee ){ } } } } } } protected abstract SocketHandler accept( SocketChannel sc ); protected abstract class SocketHandler { protected SocketHandler( SocketChannel sc ){ _channel = sc; } /** * @return true if the selector thread should stop paying attention to this */ protected abstract boolean gotData( ByteBuffer inBuf ) throws IOException ; protected abstract boolean shouldClose() throws IOException ; protected abstract void writeMoreIfWant() throws IOException; // other stuff public void registerForWrites() throws IOException { if ( D ) System.out.println( "registerForWrites" ); _register( SelectionKey.OP_WRITE ); } public void registerForReads() throws IOException { if ( D ) System.out.println( "registerForReads" ); _register( SelectionKey.OP_READ ); } private void _register( int ops ) throws IOException { SelectionKey key = _channel.keyFor( _selector ); if ( key == null || key.attachment() != this ) throw new RuntimeException( "somethins is wrong" ); if ( key.interestOps() == ops ) return; key.interestOps( ops ); _selector.wakeup(); if ( D ) System.out.println( key + " : " + key.isValid() ); } public void cancel(){ _key.cancel(); } public void pause(){ _key.interestOps( 0 ); } public InetAddress getInetAddress(){ return _channel.socket().getInetAddress(); } protected final SocketChannel _channel; private SelectionKey _key = null; } protected final int _port; protected final Selector _selector; protected final ServerSocketChannel _ssChannel; }
true
true
public void run(){ System.out.println( "Listening on post: " + _port ); final ByteBuffer readBuf = ByteBuffer.allocateDirect(1024); final ByteBuffer writeBuf = ByteBuffer.allocateDirect(1024); while ( true ){ try { _selector.select( 10 ); } catch ( IOException ioe ){ ed.log.Logger.getLogger( "nio" ).error( "couldn't select on port : " + _port , ioe ); continue; } for ( Iterator<SelectionKey> i = _selector.selectedKeys().iterator() ; i.hasNext() ; ){ SelectionKey key = i.next(); SocketChannel sc = null; SocketHandler sh = null; try { if ( D ) System.out.println( key + " read : " + key.isReadable() + " write : " + key.isWritable() ); if ( key.isAcceptable() ){ ServerSocketChannel ssc = (ServerSocketChannel)key.channel(); sc = ssc.accept(); sc.socket().setTcpNoDelay( true ); sc.configureBlocking( false ); sh = accept( sc ); sh._key = sc.register( _selector , SelectionKey.OP_READ , sh ); if ( D ) System.out.println( sc ); i.remove(); continue; } sc = (SocketChannel)key.channel(); sh = (SocketHandler)key.attachment(); if ( sh.shouldClose() ){ if ( D ) System.out.println( "\t want to close : " + sc ); Socket temp = sc.socket(); temp.shutdownInput(); temp.shutdownOutput(); temp.close(); sc.close(); key.cancel(); continue; } if ( key.isWritable() ) sh.writeMoreIfWant(); if ( key.isReadable() ){ i.remove(); if ( D ) System.out.println( "\t" + sc ); readBuf.clear(); int read = sc.read( readBuf ); if ( D ) System.out.println( "\t\t" + read ); if ( read == -1 ){ sc.close(); continue; } if ( read == 0 ) continue; readBuf.flip(); if ( sh.gotData( readBuf ) ){ key.cancel(); continue; } } } catch ( Exception e ){ if ( sc != null ){ try { sc.close(); } catch ( Exception ee ){ } } } } } }
public void run(){ System.out.println( "Listening on port: " + _port ); final ByteBuffer readBuf = ByteBuffer.allocateDirect(1024); final ByteBuffer writeBuf = ByteBuffer.allocateDirect(1024); while ( true ){ try { _selector.select( 10 ); } catch ( IOException ioe ){ ed.log.Logger.getLogger( "nio" ).error( "couldn't select on port : " + _port , ioe ); continue; } for ( Iterator<SelectionKey> i = _selector.selectedKeys().iterator() ; i.hasNext() ; ){ SelectionKey key = i.next(); SocketChannel sc = null; SocketHandler sh = null; try { if ( D ) System.out.println( key + " read : " + key.isReadable() + " write : " + key.isWritable() ); if ( key.isAcceptable() ){ ServerSocketChannel ssc = (ServerSocketChannel)key.channel(); sc = ssc.accept(); sc.socket().setTcpNoDelay( true ); sc.configureBlocking( false ); sh = accept( sc ); sh._key = sc.register( _selector , SelectionKey.OP_READ , sh ); if ( D ) System.out.println( sc ); i.remove(); continue; } sc = (SocketChannel)key.channel(); sh = (SocketHandler)key.attachment(); if ( sh.shouldClose() ){ if ( D ) System.out.println( "\t want to close : " + sc ); Socket temp = sc.socket(); temp.shutdownInput(); temp.shutdownOutput(); temp.close(); sc.close(); key.cancel(); continue; } if ( key.isWritable() ) sh.writeMoreIfWant(); if ( key.isReadable() ){ i.remove(); if ( D ) System.out.println( "\t" + sc ); readBuf.clear(); int read = sc.read( readBuf ); if ( D ) System.out.println( "\t\t" + read ); if ( read == -1 ){ sc.close(); continue; } if ( read == 0 ) continue; readBuf.flip(); if ( sh.gotData( readBuf ) ){ key.cancel(); continue; } } } catch ( Exception e ){ if ( sc != null ){ try { sc.close(); } catch ( Exception ee ){ } } } } } }
diff --git a/src/main/java/com/sixdimensions/wcm/cq/cqex/tags/GetPropertiesTag.java b/src/main/java/com/sixdimensions/wcm/cq/cqex/tags/GetPropertiesTag.java index 7b09307..6a217f1 100644 --- a/src/main/java/com/sixdimensions/wcm/cq/cqex/tags/GetPropertiesTag.java +++ b/src/main/java/com/sixdimensions/wcm/cq/cqex/tags/GetPropertiesTag.java @@ -1,139 +1,139 @@ /* * Copyright 2012 - Six Dimensions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sixdimensions.wcm.cq.cqex.tags; import java.util.Map; import javax.servlet.jsp.JspException; import org.apache.commons.lang.StringUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ValueMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tldgen.annotations.Attribute; import org.tldgen.annotations.BodyContent; import org.tldgen.annotations.Tag; /** * Tag that retrieves the properties from the resource at a path and saves them * into a page context variable as a ValueMap. * * @author dklco */ @Tag(bodyContent = BodyContent.EMPTY, example = "&lt;cqex:getProperties " + "var=\"properties\" path=\"jcr:content/myNode\" resource=\"${resource}\" />") public class GetPropertiesTag extends AttributeSettingTag { private static final Logger log = LoggerFactory .getLogger(GetPropertiesTag.class); private static final long serialVersionUID = 2906794811653608479L; /** * The path of the resource to retrieve as a ValueMap. If a resource is * specified, this is treated as a relative path, if there is no resource, * it is treated as an absolute path. */ @Attribute private String path; /** * The resource to use as a base for retrieving the properties. If this and * path are specified the properties at the sub-resource specified by the * path will be retrieved. */ @Attribute private transient Resource resource; /* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doEndTag() */ @Override public int doEndTag() throws JspException { log.trace("doEndTag"); Map<?, ?> properties = null; final SlingHttpServletRequest request = (SlingHttpServletRequest) this.pageContext .getRequest(); Resource rsrc = null; if ((this.resource != null) && !StringUtils.isEmpty(this.path)) { log.trace("Finding resource at relative path: " + this.path); rsrc = request.getResourceResolver().getResource( request.getResource(), this.path); } else if ((this.resource != null) && StringUtils.isEmpty(this.path)) { log.trace("Using resource: " + this.resource.getPath()); rsrc = this.resource; - } else if (this.path.startsWith("/")) { + } else if ((this.path != null) && this.path.startsWith("/")) { log.trace("Finding resource at absolute path: " + this.path); rsrc = request.getResourceResolver().getResource(this.path); } else { log.warn("Unable to retrieve resource, neither path nor resource specified."); } if ((rsrc != null) && !rsrc.getResourceType().equals( Resource.RESOURCE_TYPE_NON_EXISTING)) { properties = rsrc.adaptTo(ValueMap.class); this.setAttribute(this.getVar(), properties); } else { log.debug("Resource not found at path: " + this.path); } return javax.servlet.jsp.tagext.Tag.EVAL_PAGE; } /** * Gets the path of the resource to retrieve. * * @return the path of the resource to retrieve */ public String getPath() { return this.path; } /** * Gets the resource to retrieve the properties from. * * @return the resource from which to retrieve the properties */ public Resource getResource() { return this.resource; } /** * Set the path of the resource to retrieve. * * @param path * the path of the resource to retrieve */ public void setPath(final String path) { this.path = path; } /** * Set the resource to retrieve the properties from. * * @param resource * the resource from which to retrieve the properties */ public void setResource(final Resource resource) { this.resource = resource; } }
true
true
public int doEndTag() throws JspException { log.trace("doEndTag"); Map<?, ?> properties = null; final SlingHttpServletRequest request = (SlingHttpServletRequest) this.pageContext .getRequest(); Resource rsrc = null; if ((this.resource != null) && !StringUtils.isEmpty(this.path)) { log.trace("Finding resource at relative path: " + this.path); rsrc = request.getResourceResolver().getResource( request.getResource(), this.path); } else if ((this.resource != null) && StringUtils.isEmpty(this.path)) { log.trace("Using resource: " + this.resource.getPath()); rsrc = this.resource; } else if (this.path.startsWith("/")) { log.trace("Finding resource at absolute path: " + this.path); rsrc = request.getResourceResolver().getResource(this.path); } else { log.warn("Unable to retrieve resource, neither path nor resource specified."); } if ((rsrc != null) && !rsrc.getResourceType().equals( Resource.RESOURCE_TYPE_NON_EXISTING)) { properties = rsrc.adaptTo(ValueMap.class); this.setAttribute(this.getVar(), properties); } else { log.debug("Resource not found at path: " + this.path); } return javax.servlet.jsp.tagext.Tag.EVAL_PAGE; }
public int doEndTag() throws JspException { log.trace("doEndTag"); Map<?, ?> properties = null; final SlingHttpServletRequest request = (SlingHttpServletRequest) this.pageContext .getRequest(); Resource rsrc = null; if ((this.resource != null) && !StringUtils.isEmpty(this.path)) { log.trace("Finding resource at relative path: " + this.path); rsrc = request.getResourceResolver().getResource( request.getResource(), this.path); } else if ((this.resource != null) && StringUtils.isEmpty(this.path)) { log.trace("Using resource: " + this.resource.getPath()); rsrc = this.resource; } else if ((this.path != null) && this.path.startsWith("/")) { log.trace("Finding resource at absolute path: " + this.path); rsrc = request.getResourceResolver().getResource(this.path); } else { log.warn("Unable to retrieve resource, neither path nor resource specified."); } if ((rsrc != null) && !rsrc.getResourceType().equals( Resource.RESOURCE_TYPE_NON_EXISTING)) { properties = rsrc.adaptTo(ValueMap.class); this.setAttribute(this.getVar(), properties); } else { log.debug("Resource not found at path: " + this.path); } return javax.servlet.jsp.tagext.Tag.EVAL_PAGE; }
diff --git a/android/ChartBoostPlugin.java b/android/ChartBoostPlugin.java index a8fe3d4..95fbe75 100644 --- a/android/ChartBoostPlugin.java +++ b/android/ChartBoostPlugin.java @@ -1,205 +1,205 @@ package com.tealeaf.plugin.plugins; import com.tealeaf.logger; import com.tealeaf.plugin.IPlugin; import java.io.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.chartboost.sdk.*; import android.app.Activity; import android.content.Intent; import android.content.Context; import android.util.Log; import android.os.Bundle; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; public class ChartBoostPlugin implements IPlugin { private Chartboost cb; private Activity mActivity; private class PluginDelegate implements ChartboostDelegate { @Override public void didCacheMoreApps() { // TODO Auto-generated method stub } @Override public void didClickInterstitial(String arg0) { // TODO Auto-generated method stub } @Override public void didClickMoreApps() { // TODO Auto-generated method stub } @Override public void didCloseInterstitial(String arg0) { // TODO Auto-generated method stub } @Override public void didCloseMoreApps() { // TODO Auto-generated method stub } @Override public void didDismissInterstitial(String arg0) { // TODO Auto-generated method stub } @Override public void didDismissMoreApps() { // TODO Auto-generated method stub } @Override public void didFailToLoadInterstitial(String arg0) { // TODO Auto-generated method stub } @Override public void didFailToLoadMoreApps() { // TODO Auto-generated method stub } @Override public void didShowInterstitial(String arg0) { // TODO Auto-generated method stub } @Override public void didShowMoreApps() { // TODO Auto-generated method stub } @Override public boolean shouldDisplayInterstitial(String arg0) { // TODO Auto-generated method stub return false; } @Override public boolean shouldDisplayLoadingViewForMoreApps() { // TODO Auto-generated method stub return false; } @Override public boolean shouldDisplayMoreApps() { // TODO Auto-generated method stub return false; } @Override public boolean shouldRequestInterstitial(String arg0) { // TODO Auto-generated method stub return false; } @Override public boolean shouldRequestInterstitialsInFirstSession() { // TODO Auto-generated method stub return false; } @Override public boolean shouldRequestMoreApps() { // TODO Auto-generated method stub return false; } @Override public void didCacheInterstitial(String arg0) { // TODO Auto-generated method stub }; } public ChartBoostPlugin() { } public void onCreateApplication(Context applicationContext) { } public void onCreate(Activity activity, Bundle savedInstanceState) { this.mActivity = activity; PackageManager manager = activity.getPackageManager(); String appID = "", appSignature = ""; try { Bundle meta = manager.getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA).metaData; if (meta != null) { - appID = meta.getString("CHARTBOOST_APP_ID"); - appSignature = meta.getString("CHARTBOOST_APP_SIGNATURE"); + appID = meta.get("CHARTBOOST_APP_ID").toString(); + appSignature = meta.get("CHARTBOOST_APP_SIGNATURE").toString(); } } catch (Exception e) { android.util.Log.d("EXCEPTION", "" + e.getMessage()); } logger.log("{chartboost} Initializing from manifest with AppID=", appID, "and signature=", appSignature); this.cb = Chartboost.sharedChartboost(); this.cb.onCreate(activity, appID, appSignature, null); this.cb.startSession(); } public void onResume() { } public void onStart() { this.cb.onStart(mActivity); } public void onPause() { } public void onStop() { this.cb.onStop(mActivity); } public void onDestroy() { this.cb.onDestroy(mActivity); } public void onNewIntent(Intent intent) { } public void setInstallReferrer(String referrer) { } public void onActivityResult(Integer request, Integer result, Intent data) { } public boolean consumeOnBackPressed() { return true; } public void onBackPressed() { } }
true
true
public void onCreate(Activity activity, Bundle savedInstanceState) { this.mActivity = activity; PackageManager manager = activity.getPackageManager(); String appID = "", appSignature = ""; try { Bundle meta = manager.getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA).metaData; if (meta != null) { appID = meta.getString("CHARTBOOST_APP_ID"); appSignature = meta.getString("CHARTBOOST_APP_SIGNATURE"); } } catch (Exception e) { android.util.Log.d("EXCEPTION", "" + e.getMessage()); } logger.log("{chartboost} Initializing from manifest with AppID=", appID, "and signature=", appSignature); this.cb = Chartboost.sharedChartboost(); this.cb.onCreate(activity, appID, appSignature, null); this.cb.startSession(); }
public void onCreate(Activity activity, Bundle savedInstanceState) { this.mActivity = activity; PackageManager manager = activity.getPackageManager(); String appID = "", appSignature = ""; try { Bundle meta = manager.getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA).metaData; if (meta != null) { appID = meta.get("CHARTBOOST_APP_ID").toString(); appSignature = meta.get("CHARTBOOST_APP_SIGNATURE").toString(); } } catch (Exception e) { android.util.Log.d("EXCEPTION", "" + e.getMessage()); } logger.log("{chartboost} Initializing from manifest with AppID=", appID, "and signature=", appSignature); this.cb = Chartboost.sharedChartboost(); this.cb.onCreate(activity, appID, appSignature, null); this.cb.startSession(); }
diff --git a/ldapbrowser-common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterAutoEditStrategy.java b/ldapbrowser-common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterAutoEditStrategy.java index b94065b93..c93309953 100644 --- a/ldapbrowser-common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterAutoEditStrategy.java +++ b/ldapbrowser-common/src/main/java/org/apache/directory/studio/ldapbrowser/common/filtereditor/FilterAutoEditStrategy.java @@ -1,291 +1,295 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.ldapbrowser.common.filtereditor; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapAndFilterComponent; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilter; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapFilterComponent; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapNotFilterComponent; import org.apache.directory.studio.ldapbrowser.core.model.filter.LdapOrFilterComponent; import org.apache.directory.studio.ldapbrowser.core.model.filter.parser.LdapFilterParser; import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; /** * The FilterAutoEditStrategy implements the IAutoEditStrategy for the filter editor widget. * It provides smart parentesis handling when typing the filter. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class FilterAutoEditStrategy extends DefaultIndentLineAutoEditStrategy implements IAutoEditStrategy { /** The Constant INDENT_STRING. */ public static final String INDENT_STRING = " "; /** The filter parser. */ private LdapFilterParser parser; /** * Creates a new instance of FilterAutoEditStrategy. * * @param parser the filter parser */ public FilterAutoEditStrategy( LdapFilterParser parser ) { this.parser = parser; } /** * @see org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand( IDocument d, DocumentCommand c ) { super.customizeDocumentCommand( d, c ); AutoEditParameters aep = new AutoEditParameters( c.text, c.offset, c.length, c.caretOffset, c.shiftsCaret ); customizeAutoEditParameters( d.get(), aep ); c.offset = aep.offset; c.length = aep.length; c.text = aep.text; c.caretOffset = aep.caretOffset; c.shiftsCaret = aep.shiftsCaret; } /** * Customizes auto edit parameters. * * @param currentFilter the current filter * @param aep the auto edit parameters */ public void customizeAutoEditParameters( String currentFilter, AutoEditParameters aep ) { parser.parse( currentFilter ); LdapFilter filter = parser.getModel().getFilter( aep.offset ); + if ( filter == null ) + { + return; + } // check balanced parenthesis int balanced = 0; for ( int i = 0; i < currentFilter.length(); i++ ) { if ( currentFilter.charAt( i ) == '(' ) { balanced++; } else if ( currentFilter.charAt( i ) == ')' ) { balanced--; } } if ( aep.length > 0 && ( aep.text == null || "".equals( aep.text ) ) ) { // delete surrounding parenthesis after deleting the last character if ( filter.toString().length() - aep.length == 2 && filter.getStartToken() != null && filter.getStopToken() != null && aep.offset >= filter.getStartToken().getOffset() + filter.getStartToken().getLength() && aep.offset + aep.length <= filter.getStopToken().getOffset() ) { if ( filter.toString().length() - aep.length == 2 ) { aep.offset -= 1; aep.length += 2; aep.caretOffset = aep.offset; aep.shiftsCaret = false; } } // delete closing parenthesis after deleting the opening parenthesis if ( filter.toString().length() - aep.length == 1 && filter.getStartToken() != null && filter.getStopToken() != null && aep.offset == filter.getStartToken().getOffset() ) { aep.length += 1; aep.caretOffset = aep.offset; aep.shiftsCaret = false; } } if ( (aep.length == 0 || aep.length==currentFilter.length()) && aep.text != null && !"".equals( aep.text ) ) { boolean isNewFilter = aep.text.equals( "(" ); boolean isNewNestedFilter = aep.text.equals( "&" ) || aep.text.equals( "|" ) || aep.text.equals( "!" ); boolean isSurroundNew = false; boolean isSurroundNested = false; boolean isSurroundBeforeOtherFilter = false; boolean isSurroundAfterOtherFilter = false; if( !Character.isWhitespace( aep.text.charAt( 0 ) ) && !aep.text.startsWith( "(" ) && !aep.text.endsWith( ")" ) ) { // isSurroundNew isSurroundNew = aep.offset == 0; // isSurroundNested if ( filter.getStartToken() != null && filter.getFilterComponent() != null && ( filter.getFilterComponent() instanceof LdapAndFilterComponent || filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ) ) { LdapFilterComponent fc = filter.getFilterComponent(); LdapFilter[] filters = fc.getFilters(); if ( filters.length == 0 && aep.offset > fc.getStartToken().getOffset() ) { // no nested filter yet isSurroundNested = true; } if ( filters.length > 0 && aep.offset > fc.getStartToken().getOffset() && aep.offset < filters[0].getStartToken().getOffset() ) { // before first nested filter isSurroundNested = true; } if ( filters.length > 0 && aep.offset > filters[filters.length - 1].getStopToken().getOffset() && aep.offset <= filter.getStopToken().getOffset() ) { // after last nested filter isSurroundNested = true; } for ( int i = 0; i < filters.length; i++ ) { if ( filters.length > i + 1 ) { if ( aep.offset > filters[i].getStopToken().getOffset() && aep.offset <= filters[i + 1].getStopToken().getOffset() ) { // between nested filter isSurroundNested = true; } } } } // isSurroundBeforeOtherFilter isSurroundBeforeOtherFilter = filter.getStartToken() != null && aep.offset == filter.getStartToken().getOffset(); // isSurroundAfterOtherFilter isSurroundAfterOtherFilter = filter.getStopToken() != null && aep.offset == filter.getStopToken().getOffset() && ( filter.getFilterComponent() instanceof LdapAndFilterComponent || filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ); } //System.out.println("isSurroundNew="+isSurroundNew+", isSurroundNested="+isSurroundNested+", isSurroundAfterOtherFilter="+isSurroundAfterOtherFilter+", isSurroundBeforeOtherFilter="+isSurroundBeforeOtherFilter); // add opening parenthesis '(' if ( isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter ) { aep.text = "(" + aep.text; aep.caretOffset = aep.offset + aep.text.length(); aep.shiftsCaret = false; } // add parenthesis for nested filters if ( isNewNestedFilter ) { aep.text = aep.text + "()"; aep.caretOffset = aep.offset + aep.text.length() - 1; aep.shiftsCaret = false; } // add closing parenthesis ')' if ( isNewFilter || isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter ) { if ( balanced == 0 ) { aep.text = aep.text + ")"; if( aep.caretOffset == -1 ) { aep.caretOffset = aep.offset + aep.text.length() - 1; aep.shiftsCaret = false; } } } // translate tab to IDENT_STRING if ( aep.text.equals( "\t" ) ) { aep.text = INDENT_STRING; } } //System.out.println( "aep='"+aep.text+"',"+aep.offset+","+aep.length+","+aep.caretOffset+","+aep.shiftsCaret+"; balanced="+balanced+"; filter='"+filter.toString()+"'" ); } /** * Helper class. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public static class AutoEditParameters { /** The text. */ public String text; /** The offset. */ public int offset; /** The length. */ public int length; /** The caret offset. */ public int caretOffset; /** The shifts caret flag. */ public boolean shiftsCaret; /** * Creates a new instance of AutoEditParameters. * * @param text the text * @param offset the offset * @param length the length * @param caretOffset the caret offset * @param shiftsCaret the shifts caret flag */ public AutoEditParameters( String text, int offset, int length, int caretOffset, boolean shiftsCaret ) { this.text = text; this.offset = offset; this.length = length; this.caretOffset = caretOffset; this.shiftsCaret = shiftsCaret; } } }
true
true
public void customizeAutoEditParameters( String currentFilter, AutoEditParameters aep ) { parser.parse( currentFilter ); LdapFilter filter = parser.getModel().getFilter( aep.offset ); // check balanced parenthesis int balanced = 0; for ( int i = 0; i < currentFilter.length(); i++ ) { if ( currentFilter.charAt( i ) == '(' ) { balanced++; } else if ( currentFilter.charAt( i ) == ')' ) { balanced--; } } if ( aep.length > 0 && ( aep.text == null || "".equals( aep.text ) ) ) { // delete surrounding parenthesis after deleting the last character if ( filter.toString().length() - aep.length == 2 && filter.getStartToken() != null && filter.getStopToken() != null && aep.offset >= filter.getStartToken().getOffset() + filter.getStartToken().getLength() && aep.offset + aep.length <= filter.getStopToken().getOffset() ) { if ( filter.toString().length() - aep.length == 2 ) { aep.offset -= 1; aep.length += 2; aep.caretOffset = aep.offset; aep.shiftsCaret = false; } } // delete closing parenthesis after deleting the opening parenthesis if ( filter.toString().length() - aep.length == 1 && filter.getStartToken() != null && filter.getStopToken() != null && aep.offset == filter.getStartToken().getOffset() ) { aep.length += 1; aep.caretOffset = aep.offset; aep.shiftsCaret = false; } } if ( (aep.length == 0 || aep.length==currentFilter.length()) && aep.text != null && !"".equals( aep.text ) ) { boolean isNewFilter = aep.text.equals( "(" ); boolean isNewNestedFilter = aep.text.equals( "&" ) || aep.text.equals( "|" ) || aep.text.equals( "!" ); boolean isSurroundNew = false; boolean isSurroundNested = false; boolean isSurroundBeforeOtherFilter = false; boolean isSurroundAfterOtherFilter = false; if( !Character.isWhitespace( aep.text.charAt( 0 ) ) && !aep.text.startsWith( "(" ) && !aep.text.endsWith( ")" ) ) { // isSurroundNew isSurroundNew = aep.offset == 0; // isSurroundNested if ( filter.getStartToken() != null && filter.getFilterComponent() != null && ( filter.getFilterComponent() instanceof LdapAndFilterComponent || filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ) ) { LdapFilterComponent fc = filter.getFilterComponent(); LdapFilter[] filters = fc.getFilters(); if ( filters.length == 0 && aep.offset > fc.getStartToken().getOffset() ) { // no nested filter yet isSurroundNested = true; } if ( filters.length > 0 && aep.offset > fc.getStartToken().getOffset() && aep.offset < filters[0].getStartToken().getOffset() ) { // before first nested filter isSurroundNested = true; } if ( filters.length > 0 && aep.offset > filters[filters.length - 1].getStopToken().getOffset() && aep.offset <= filter.getStopToken().getOffset() ) { // after last nested filter isSurroundNested = true; } for ( int i = 0; i < filters.length; i++ ) { if ( filters.length > i + 1 ) { if ( aep.offset > filters[i].getStopToken().getOffset() && aep.offset <= filters[i + 1].getStopToken().getOffset() ) { // between nested filter isSurroundNested = true; } } } } // isSurroundBeforeOtherFilter isSurroundBeforeOtherFilter = filter.getStartToken() != null && aep.offset == filter.getStartToken().getOffset(); // isSurroundAfterOtherFilter isSurroundAfterOtherFilter = filter.getStopToken() != null && aep.offset == filter.getStopToken().getOffset() && ( filter.getFilterComponent() instanceof LdapAndFilterComponent || filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ); } //System.out.println("isSurroundNew="+isSurroundNew+", isSurroundNested="+isSurroundNested+", isSurroundAfterOtherFilter="+isSurroundAfterOtherFilter+", isSurroundBeforeOtherFilter="+isSurroundBeforeOtherFilter); // add opening parenthesis '(' if ( isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter ) { aep.text = "(" + aep.text; aep.caretOffset = aep.offset + aep.text.length(); aep.shiftsCaret = false; } // add parenthesis for nested filters if ( isNewNestedFilter ) { aep.text = aep.text + "()"; aep.caretOffset = aep.offset + aep.text.length() - 1; aep.shiftsCaret = false; } // add closing parenthesis ')' if ( isNewFilter || isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter ) { if ( balanced == 0 ) { aep.text = aep.text + ")"; if( aep.caretOffset == -1 ) { aep.caretOffset = aep.offset + aep.text.length() - 1; aep.shiftsCaret = false; } } } // translate tab to IDENT_STRING if ( aep.text.equals( "\t" ) ) { aep.text = INDENT_STRING; } } //System.out.println( "aep='"+aep.text+"',"+aep.offset+","+aep.length+","+aep.caretOffset+","+aep.shiftsCaret+"; balanced="+balanced+"; filter='"+filter.toString()+"'" ); }
public void customizeAutoEditParameters( String currentFilter, AutoEditParameters aep ) { parser.parse( currentFilter ); LdapFilter filter = parser.getModel().getFilter( aep.offset ); if ( filter == null ) { return; } // check balanced parenthesis int balanced = 0; for ( int i = 0; i < currentFilter.length(); i++ ) { if ( currentFilter.charAt( i ) == '(' ) { balanced++; } else if ( currentFilter.charAt( i ) == ')' ) { balanced--; } } if ( aep.length > 0 && ( aep.text == null || "".equals( aep.text ) ) ) { // delete surrounding parenthesis after deleting the last character if ( filter.toString().length() - aep.length == 2 && filter.getStartToken() != null && filter.getStopToken() != null && aep.offset >= filter.getStartToken().getOffset() + filter.getStartToken().getLength() && aep.offset + aep.length <= filter.getStopToken().getOffset() ) { if ( filter.toString().length() - aep.length == 2 ) { aep.offset -= 1; aep.length += 2; aep.caretOffset = aep.offset; aep.shiftsCaret = false; } } // delete closing parenthesis after deleting the opening parenthesis if ( filter.toString().length() - aep.length == 1 && filter.getStartToken() != null && filter.getStopToken() != null && aep.offset == filter.getStartToken().getOffset() ) { aep.length += 1; aep.caretOffset = aep.offset; aep.shiftsCaret = false; } } if ( (aep.length == 0 || aep.length==currentFilter.length()) && aep.text != null && !"".equals( aep.text ) ) { boolean isNewFilter = aep.text.equals( "(" ); boolean isNewNestedFilter = aep.text.equals( "&" ) || aep.text.equals( "|" ) || aep.text.equals( "!" ); boolean isSurroundNew = false; boolean isSurroundNested = false; boolean isSurroundBeforeOtherFilter = false; boolean isSurroundAfterOtherFilter = false; if( !Character.isWhitespace( aep.text.charAt( 0 ) ) && !aep.text.startsWith( "(" ) && !aep.text.endsWith( ")" ) ) { // isSurroundNew isSurroundNew = aep.offset == 0; // isSurroundNested if ( filter.getStartToken() != null && filter.getFilterComponent() != null && ( filter.getFilterComponent() instanceof LdapAndFilterComponent || filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ) ) { LdapFilterComponent fc = filter.getFilterComponent(); LdapFilter[] filters = fc.getFilters(); if ( filters.length == 0 && aep.offset > fc.getStartToken().getOffset() ) { // no nested filter yet isSurroundNested = true; } if ( filters.length > 0 && aep.offset > fc.getStartToken().getOffset() && aep.offset < filters[0].getStartToken().getOffset() ) { // before first nested filter isSurroundNested = true; } if ( filters.length > 0 && aep.offset > filters[filters.length - 1].getStopToken().getOffset() && aep.offset <= filter.getStopToken().getOffset() ) { // after last nested filter isSurroundNested = true; } for ( int i = 0; i < filters.length; i++ ) { if ( filters.length > i + 1 ) { if ( aep.offset > filters[i].getStopToken().getOffset() && aep.offset <= filters[i + 1].getStopToken().getOffset() ) { // between nested filter isSurroundNested = true; } } } } // isSurroundBeforeOtherFilter isSurroundBeforeOtherFilter = filter.getStartToken() != null && aep.offset == filter.getStartToken().getOffset(); // isSurroundAfterOtherFilter isSurroundAfterOtherFilter = filter.getStopToken() != null && aep.offset == filter.getStopToken().getOffset() && ( filter.getFilterComponent() instanceof LdapAndFilterComponent || filter.getFilterComponent() instanceof LdapOrFilterComponent || filter.getFilterComponent() instanceof LdapNotFilterComponent ); } //System.out.println("isSurroundNew="+isSurroundNew+", isSurroundNested="+isSurroundNested+", isSurroundAfterOtherFilter="+isSurroundAfterOtherFilter+", isSurroundBeforeOtherFilter="+isSurroundBeforeOtherFilter); // add opening parenthesis '(' if ( isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter ) { aep.text = "(" + aep.text; aep.caretOffset = aep.offset + aep.text.length(); aep.shiftsCaret = false; } // add parenthesis for nested filters if ( isNewNestedFilter ) { aep.text = aep.text + "()"; aep.caretOffset = aep.offset + aep.text.length() - 1; aep.shiftsCaret = false; } // add closing parenthesis ')' if ( isNewFilter || isSurroundNew || isSurroundNested || isSurroundAfterOtherFilter || isSurroundBeforeOtherFilter ) { if ( balanced == 0 ) { aep.text = aep.text + ")"; if( aep.caretOffset == -1 ) { aep.caretOffset = aep.offset + aep.text.length() - 1; aep.shiftsCaret = false; } } } // translate tab to IDENT_STRING if ( aep.text.equals( "\t" ) ) { aep.text = INDENT_STRING; } } //System.out.println( "aep='"+aep.text+"',"+aep.offset+","+aep.length+","+aep.caretOffset+","+aep.shiftsCaret+"; balanced="+balanced+"; filter='"+filter.toString()+"'" ); }
diff --git a/loci/formats/CoreMetadata.java b/loci/formats/CoreMetadata.java index ec841322d..3ff5cf4e3 100644 --- a/loci/formats/CoreMetadata.java +++ b/loci/formats/CoreMetadata.java @@ -1,71 +1,71 @@ // // CoreMetadata.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.util.Hashtable; /** * Encompasses core metadata values. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/CoreMetadata.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/CoreMetadata.java">SVN</a></dd></dl> */ public class CoreMetadata { public int[] sizeX, sizeY, sizeZ, sizeC, sizeT; public int[] thumbSizeX, thumbSizeY; public int[] pixelType; public int[] imageCount; public int[][] cLengths; public String[][] cTypes; public String[] currentOrder; public boolean[] orderCertain, rgb, littleEndian, interleaved; public boolean[] indexed, falseColor, metadataComplete; public Hashtable[] seriesMetadata; public CoreMetadata(int series) { sizeX = new int[series]; sizeY = new int[series]; sizeZ = new int[series]; sizeC = new int[series]; sizeT = new int[series]; thumbSizeX = new int[series]; thumbSizeY = new int[series]; pixelType = new int[series]; imageCount = new int[series]; cLengths = new int[series][]; cTypes = new String[series][]; currentOrder = new String[series]; orderCertain = new boolean[series]; rgb = new boolean[series]; littleEndian = new boolean[series]; interleaved = new boolean[series]; indexed = new boolean[series]; falseColor = new boolean[series]; metadataComplete = new boolean[series]; - seriesMetadata = new Hashtable[series]; for (int i=0; i<series; i++) - seriesMetadata[i] = new Hashtable(); + seriesMetadata = new Hashtable[series]; + for (int i=0; i<series; i++) seriesMetadata[i] = new Hashtable(); } }
true
true
public CoreMetadata(int series) { sizeX = new int[series]; sizeY = new int[series]; sizeZ = new int[series]; sizeC = new int[series]; sizeT = new int[series]; thumbSizeX = new int[series]; thumbSizeY = new int[series]; pixelType = new int[series]; imageCount = new int[series]; cLengths = new int[series][]; cTypes = new String[series][]; currentOrder = new String[series]; orderCertain = new boolean[series]; rgb = new boolean[series]; littleEndian = new boolean[series]; interleaved = new boolean[series]; indexed = new boolean[series]; falseColor = new boolean[series]; metadataComplete = new boolean[series]; seriesMetadata = new Hashtable[series]; for (int i=0; i<series; i++) seriesMetadata[i] = new Hashtable(); }
public CoreMetadata(int series) { sizeX = new int[series]; sizeY = new int[series]; sizeZ = new int[series]; sizeC = new int[series]; sizeT = new int[series]; thumbSizeX = new int[series]; thumbSizeY = new int[series]; pixelType = new int[series]; imageCount = new int[series]; cLengths = new int[series][]; cTypes = new String[series][]; currentOrder = new String[series]; orderCertain = new boolean[series]; rgb = new boolean[series]; littleEndian = new boolean[series]; interleaved = new boolean[series]; indexed = new boolean[series]; falseColor = new boolean[series]; metadataComplete = new boolean[series]; seriesMetadata = new Hashtable[series]; for (int i=0; i<series; i++) seriesMetadata[i] = new Hashtable(); }
diff --git a/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java b/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java index 79c1129e..413bcc96 100644 --- a/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java +++ b/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java @@ -1,608 +1,607 @@ package data_objects.drivers; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.Date; import java.sql.Driver; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.Map; import java.util.Properties; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.jruby.Ruby; import org.jruby.RubyBigDecimal; import org.jruby.RubyBignum; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyFloat; import org.jruby.RubyHash; import org.jruby.RubyNumeric; import org.jruby.RubyObjectAdapter; import org.jruby.RubyProc; import org.jruby.RubyRegexp; import org.jruby.RubyString; import org.jruby.RubyTime; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.marshal.UnmarshalStream; import org.jruby.util.ByteList; import data_objects.RubyType; /** * * @author alexbcoles * @author mkristian */ public abstract class AbstractDriverDefinition implements DriverDefinition { // assuming that API is thread safe protected static final RubyObjectAdapter API = JavaEmbedUtils .newObjectAdapter(); protected final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); private final static BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); private final static BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); private final static long MRI_FIXNUM_MAX = (1L<<32) - 1; private final static long MRI_FIXNUM_MIN = -1 * MRI_FIXNUM_MAX - 1; private final String scheme; private final String jdbcScheme; private final String moduleName; private final Driver driver; protected AbstractDriverDefinition(String scheme, String moduleName, String jdbcDriver) { this(scheme, scheme, moduleName, jdbcDriver); } protected AbstractDriverDefinition(String scheme, String jdbcScheme, String moduleName, String jdbcDriver) { this.scheme = scheme; this.jdbcScheme = jdbcScheme; this.moduleName = moduleName; try { this.driver = (Driver) Thread.currentThread().getContextClassLoader().loadClass(jdbcDriver).newInstance(); } catch (InstantiationException e) { throw new RuntimeException("should not happen", e); } catch (IllegalAccessException e) { throw new RuntimeException("should not happen", e); } catch (ClassNotFoundException e) { throw new RuntimeException("should not happen", e); } } public String getModuleName() { return this.moduleName; } public String getErrorName() { return this.moduleName + "Error"; } public Connection getConnection(String uri, Properties properties) throws SQLException{ return driver.connect(uri, properties); } @SuppressWarnings("unchecked") public URI parseConnectionURI(IRubyObject connection_uri) throws URISyntaxException, UnsupportedEncodingException { URI uri; if ("DataObjects::URI".equals(connection_uri.getType().getName())) { String query; StringBuffer userInfo = new StringBuffer(); verifyScheme(stringOrNull(API.callMethod(connection_uri, "scheme"))); String user = stringOrNull(API.callMethod(connection_uri, "user")); String password = stringOrNull(API.callMethod(connection_uri, "password")); String host = stringOrNull(API.callMethod(connection_uri, "host")); int port = intOrMinusOne(API.callMethod(connection_uri, "port")); String path = stringOrNull(API.callMethod(connection_uri, "path")); IRubyObject query_values = API.callMethod(connection_uri, "query"); String fragment = stringOrNull(API.callMethod(connection_uri, "fragment")); if (user != null && !"".equals(user)) { userInfo.append(user); if (password != null && !"".equals(password)) { userInfo.append(":").append(password); } } if (query_values.isNil()) { query = null; } else if (query_values instanceof RubyHash) { query = mapToQueryString(query_values.convertToHash()); } else { query = API.callMethod(query_values, "to_s").asJavaString(); } if (host != null && !"".equals(host)) { // a client/server database (e.g. MySQL, PostgreSQL, MS // SQLServer) String normalizedPath; if (path != null && path.length() > 0 && path.charAt(0) != '/') { normalizedPath = '/' + path; } else { normalizedPath = path; } uri = new URI(this.jdbcScheme, (userInfo.length() > 0 ? userInfo.toString() : null), host, port, normalizedPath, query, fragment); } else { // an embedded / file-based database (e.g. SQLite3, Derby // (embedded mode), HSQLDB - use opaque uri uri = new URI(this.jdbcScheme, path, fragment); } } else { // If connection_uri comes in as a string, we just pass it // through uri = new URI(connection_uri.asJavaString()); } return uri; } protected void verifyScheme(String scheme) { if (!this.scheme.equals(scheme)) { throw new RuntimeException("scheme mismatch, expected: " + this.scheme + " but got: " + scheme); } } /** * Convert a map of key/values to a URI query string * * @param map * @return * @throws java.io.UnsupportedEncodingException */ private String mapToQueryString(Map<Object, Object> map) throws UnsupportedEncodingException { StringBuffer querySb = new StringBuffer(); for (Map.Entry<Object, Object> pairs: map.entrySet()){ String key = (pairs.getKey() != null) ? pairs.getKey().toString() : ""; String value = (pairs.getValue() != null) ? pairs.getValue() .toString() : ""; querySb.append(java.net.URLEncoder.encode(key, "UTF-8")) .append("="); querySb.append(java.net.URLEncoder.encode(value, "UTF-8")); } return querySb.toString(); } public RaiseException newDriverError(Ruby runtime, String message) { RubyClass driverError = runtime.getClass(getErrorName()); return new RaiseException(runtime, driverError, message, true); } public RaiseException newDriverError(Ruby runtime, SQLException exception) { return newDriverError(runtime, exception, null); } public RaiseException newDriverError(Ruby runtime, SQLException exception, java.sql.Statement statement) { RubyClass driverError = runtime.getClass(getErrorName()); int code = exception.getErrorCode(); StringBuffer sb = new StringBuffer("("); // Append the Vendor Code, if there is one // TODO: parse vendor exception codes // TODO: replace 'vendor' with vendor name if (code > 0) sb.append("vendor_errno=").append(code).append(", "); sb.append("sql_state=").append(exception.getSQLState()).append(") "); sb.append(exception.getLocalizedMessage()); if (statement != null) sb.append("\nQuery: ").append(statementToString(statement)); return new RaiseException(runtime, driverError, sb.toString(), true); } public RubyObjectAdapter getObjectAdapter() { return API; } public RubyType jdbcTypeToRubyType(int type, int precision, int scale) { return RubyType.jdbcTypeToRubyType(type, scale); } public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: try { // in most cases integers will fit into long type // and therefore should be faster to use getLong long lng = rs.getLong(col); if (rs.wasNull()) { return runtime.getNil(); } // return RubyNumeric.int2fix(runtime, lng); // // Currently problematic as JRUBY has different boundaries for // Bignum/Fixnum: see http://jira.codehaus.org/browse/JRUBY-1587 if (lng >= MRI_FIXNUM_MAX || lng < MRI_FIXNUM_MIN) { return RubyBignum.newBignum(runtime, lng); } return RubyFixnum.newFixnum(runtime, lng); } catch (SQLException sqle) { // if getLong failed then use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); } case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, sqlDateToDateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See // http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html try { dt = rs.getTimestamp(col); } catch (SQLException ignored) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, sqlTimestampToDateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Timestamp ts = rs.getTimestamp(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, sqlTimestampToDateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.fastGetModule("DataObjects"), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: BigInteger big = ((RubyBignum) arg).getValue(); if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) { // set as big decimal ps.setBigDecimal(idx, new BigDecimal(((RubyBignum) arg).getValue())); } else { // set as long ps.setLong(idx, ((RubyBignum) arg).getLongValue()); } break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(IRubyObject doConn, Connection conn, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String quoteByteArray(IRubyObject connection, IRubyObject value) { return quoteString(value.asJavaString()); } public String statementToString(Statement s) { return s.toString(); } protected static DateTime sqlDateToDateTime(Date date) { - date.getYear(); if (date == null) return null; else return new DateTime(date.getYear()+1900, date.getMonth()+1, date.getDate(), 0, 0, 0, 0); } protected static DateTime sqlTimestampToDateTime(Timestamp ts) { if (ts == null) return null; return new DateTime(ts.getYear()+1900, ts.getMonth()+1, ts.getDate(), ts.getHours(), ts.getMinutes(), ts.getSeconds(), ts.getNanos()/1000000); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { // TODO: why in this case nil is returned? if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; // } }
true
true
public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: try { // in most cases integers will fit into long type // and therefore should be faster to use getLong long lng = rs.getLong(col); if (rs.wasNull()) { return runtime.getNil(); } // return RubyNumeric.int2fix(runtime, lng); // // Currently problematic as JRUBY has different boundaries for // Bignum/Fixnum: see http://jira.codehaus.org/browse/JRUBY-1587 if (lng >= MRI_FIXNUM_MAX || lng < MRI_FIXNUM_MIN) { return RubyBignum.newBignum(runtime, lng); } return RubyFixnum.newFixnum(runtime, lng); } catch (SQLException sqle) { // if getLong failed then use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); } case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, sqlDateToDateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See // http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html try { dt = rs.getTimestamp(col); } catch (SQLException ignored) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, sqlTimestampToDateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Timestamp ts = rs.getTimestamp(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, sqlTimestampToDateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.fastGetModule("DataObjects"), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: BigInteger big = ((RubyBignum) arg).getValue(); if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) { // set as big decimal ps.setBigDecimal(idx, new BigDecimal(((RubyBignum) arg).getValue())); } else { // set as long ps.setLong(idx, ((RubyBignum) arg).getLongValue()); } break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(IRubyObject doConn, Connection conn, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String quoteByteArray(IRubyObject connection, IRubyObject value) { return quoteString(value.asJavaString()); } public String statementToString(Statement s) { return s.toString(); } protected static DateTime sqlDateToDateTime(Date date) { date.getYear(); if (date == null) return null; else return new DateTime(date.getYear()+1900, date.getMonth()+1, date.getDate(), 0, 0, 0, 0); } protected static DateTime sqlTimestampToDateTime(Timestamp ts) { if (ts == null) return null; return new DateTime(ts.getYear()+1900, ts.getMonth()+1, ts.getDate(), ts.getHours(), ts.getMinutes(), ts.getSeconds(), ts.getNanos()/1000000); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { // TODO: why in this case nil is returned? if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; // } }
public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: try { // in most cases integers will fit into long type // and therefore should be faster to use getLong long lng = rs.getLong(col); if (rs.wasNull()) { return runtime.getNil(); } // return RubyNumeric.int2fix(runtime, lng); // // Currently problematic as JRUBY has different boundaries for // Bignum/Fixnum: see http://jira.codehaus.org/browse/JRUBY-1587 if (lng >= MRI_FIXNUM_MAX || lng < MRI_FIXNUM_MIN) { return RubyBignum.newBignum(runtime, lng); } return RubyFixnum.newFixnum(runtime, lng); } catch (SQLException sqle) { // if getLong failed then use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); } case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, sqlDateToDateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See // http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html try { dt = rs.getTimestamp(col); } catch (SQLException ignored) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, sqlTimestampToDateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Timestamp ts = rs.getTimestamp(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, sqlTimestampToDateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.fastGetModule("DataObjects"), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: BigInteger big = ((RubyBignum) arg).getValue(); if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) { // set as big decimal ps.setBigDecimal(idx, new BigDecimal(((RubyBignum) arg).getValue())); } else { // set as long ps.setLong(idx, ((RubyBignum) arg).getLongValue()); } break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(IRubyObject doConn, Connection conn, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String quoteByteArray(IRubyObject connection, IRubyObject value) { return quoteString(value.asJavaString()); } public String statementToString(Statement s) { return s.toString(); } protected static DateTime sqlDateToDateTime(Date date) { if (date == null) return null; else return new DateTime(date.getYear()+1900, date.getMonth()+1, date.getDate(), 0, 0, 0, 0); } protected static DateTime sqlTimestampToDateTime(Timestamp ts) { if (ts == null) return null; return new DateTime(ts.getYear()+1900, ts.getMonth()+1, ts.getDate(), ts.getHours(), ts.getMinutes(), ts.getSeconds(), ts.getNanos()/1000000); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { // TODO: why in this case nil is returned? if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; // } }
diff --git a/rexster-extensions/src/main/java/com/whysearchtwice/rexster/extension/SearchExtension.java b/rexster-extensions/src/main/java/com/whysearchtwice/rexster/extension/SearchExtension.java index c7f4f1f..0dca17c 100644 --- a/rexster-extensions/src/main/java/com/whysearchtwice/rexster/extension/SearchExtension.java +++ b/rexster-extensions/src/main/java/com/whysearchtwice/rexster/extension/SearchExtension.java @@ -1,107 +1,107 @@ package com.whysearchtwice.rexster.extension; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.gremlin.groovy.Gremlin; import com.tinkerpop.gremlin.java.GremlinPipeline; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.util.iterators.SingleIterator; import com.tinkerpop.rexster.RexsterResourceContext; import com.tinkerpop.rexster.extension.ExtensionDefinition; import com.tinkerpop.rexster.extension.ExtensionDescriptor; import com.tinkerpop.rexster.extension.ExtensionNaming; import com.tinkerpop.rexster.extension.ExtensionPoint; import com.tinkerpop.rexster.extension.ExtensionRequestParameter; import com.tinkerpop.rexster.extension.ExtensionResponse; import com.tinkerpop.rexster.extension.HttpMethod; import com.tinkerpop.rexster.extension.RexsterContext; import com.whysearchtwice.container.PageView; @ExtensionNaming(name = SearchExtension.NAME, namespace = AbstractParsleyExtension.NAMESPACE) public class SearchExtension extends AbstractParsleyExtension { public static final String NAME = "search"; @ExtensionDefinition(extensionPoint = ExtensionPoint.GRAPH, method = HttpMethod.GET) @ExtensionDescriptor(description = "Get the results of a search") public ExtensionResponse searchVertices( @RexsterContext RexsterResourceContext context, @RexsterContext Graph graph, @ExtensionRequestParameter(name = "userGuid", defaultValue = "", description = "The user to retrieve information for") String userGuid, @ExtensionRequestParameter(name = "domain", defaultValue = "", description = "Retrieve pages with this domain") String domain, @ExtensionRequestParameter(name = "openTime", defaultValue = "", description = "The middle of a time based query") String openTime, @ExtensionRequestParameter(name = "timeRange", defaultValue = "30", description = "The range of time to search around openTime (openTime +- timeRange/2)") Integer timeRange, @ExtensionRequestParameter(name = "timeRangeUnits", defaultValue = "minutes", description = "hours, minutes, seconds") String units) { // Catch some errors if (openTime.equals("")) { return ExtensionResponse.error("You should specify an openTime"); } else if (userGuid.equals("")) { return ExtensionResponse.error("You should specify a userGuid"); } Vertex user = graph.getVertex(userGuid); if (user == null) { return ExtensionResponse.error("Invalid userGuid"); } // Manipulate parameters Calendar pageOpenTime = Calendar.getInstance(); pageOpenTime.setTimeInMillis(Long.parseLong(openTime)); timeRange = adjustTimeRange(timeRange, units); List<PageView> pages = new ArrayList<PageView>(); // Perform search Pipe pipe = Gremlin.compile("_().out('owns').out('viewed')"); pipe.setStarts(new SingleIterator<Vertex>(user)); for (Object result : pipe) { if (result instanceof Vertex) { Vertex v = (Vertex) result; PageView pv = new PageView(v); // Add a reference to the parent and successors if edges exist for (Vertex neighbor : v.getVertices(Direction.OUT, "childOf")) { - pv.setProperty("parent", neighbor.getId()); + pv.setProperty("parentId", neighbor.getId().toString()); } for (Vertex neighbor : v.getVertices(Direction.OUT, "successorTo")) { - pv.setProperty("predecessor", neighbor.getId()); + pv.setProperty("predecessorId", neighbor.getId().toString()); } pages.add(pv); } } // Turn list into JSON to return String listAsJSON = "["; for(PageView pv : pages) { listAsJSON += pv.toString() + ", "; } listAsJSON = listAsJSON.substring(0, listAsJSON.length()-2); listAsJSON += "]"; // Map to store the results Map<String, String> map = new HashMap<String, String>(); map.put("results", listAsJSON); return ExtensionResponse.ok(map); } private int adjustTimeRange(int timeRange, String units) { if (units.equals("seconds")) { return timeRange * 1; } else if (units.equals("minutes")) { return timeRange * 1 * 60; } else if (units.equals("hours")) { return timeRange * 1 * 60 * 60; } else { return timeRange; } } }
false
true
public ExtensionResponse searchVertices( @RexsterContext RexsterResourceContext context, @RexsterContext Graph graph, @ExtensionRequestParameter(name = "userGuid", defaultValue = "", description = "The user to retrieve information for") String userGuid, @ExtensionRequestParameter(name = "domain", defaultValue = "", description = "Retrieve pages with this domain") String domain, @ExtensionRequestParameter(name = "openTime", defaultValue = "", description = "The middle of a time based query") String openTime, @ExtensionRequestParameter(name = "timeRange", defaultValue = "30", description = "The range of time to search around openTime (openTime +- timeRange/2)") Integer timeRange, @ExtensionRequestParameter(name = "timeRangeUnits", defaultValue = "minutes", description = "hours, minutes, seconds") String units) { // Catch some errors if (openTime.equals("")) { return ExtensionResponse.error("You should specify an openTime"); } else if (userGuid.equals("")) { return ExtensionResponse.error("You should specify a userGuid"); } Vertex user = graph.getVertex(userGuid); if (user == null) { return ExtensionResponse.error("Invalid userGuid"); } // Manipulate parameters Calendar pageOpenTime = Calendar.getInstance(); pageOpenTime.setTimeInMillis(Long.parseLong(openTime)); timeRange = adjustTimeRange(timeRange, units); List<PageView> pages = new ArrayList<PageView>(); // Perform search Pipe pipe = Gremlin.compile("_().out('owns').out('viewed')"); pipe.setStarts(new SingleIterator<Vertex>(user)); for (Object result : pipe) { if (result instanceof Vertex) { Vertex v = (Vertex) result; PageView pv = new PageView(v); // Add a reference to the parent and successors if edges exist for (Vertex neighbor : v.getVertices(Direction.OUT, "childOf")) { pv.setProperty("parent", neighbor.getId()); } for (Vertex neighbor : v.getVertices(Direction.OUT, "successorTo")) { pv.setProperty("predecessor", neighbor.getId()); } pages.add(pv); } } // Turn list into JSON to return String listAsJSON = "["; for(PageView pv : pages) { listAsJSON += pv.toString() + ", "; } listAsJSON = listAsJSON.substring(0, listAsJSON.length()-2); listAsJSON += "]"; // Map to store the results Map<String, String> map = new HashMap<String, String>(); map.put("results", listAsJSON); return ExtensionResponse.ok(map); }
public ExtensionResponse searchVertices( @RexsterContext RexsterResourceContext context, @RexsterContext Graph graph, @ExtensionRequestParameter(name = "userGuid", defaultValue = "", description = "The user to retrieve information for") String userGuid, @ExtensionRequestParameter(name = "domain", defaultValue = "", description = "Retrieve pages with this domain") String domain, @ExtensionRequestParameter(name = "openTime", defaultValue = "", description = "The middle of a time based query") String openTime, @ExtensionRequestParameter(name = "timeRange", defaultValue = "30", description = "The range of time to search around openTime (openTime +- timeRange/2)") Integer timeRange, @ExtensionRequestParameter(name = "timeRangeUnits", defaultValue = "minutes", description = "hours, minutes, seconds") String units) { // Catch some errors if (openTime.equals("")) { return ExtensionResponse.error("You should specify an openTime"); } else if (userGuid.equals("")) { return ExtensionResponse.error("You should specify a userGuid"); } Vertex user = graph.getVertex(userGuid); if (user == null) { return ExtensionResponse.error("Invalid userGuid"); } // Manipulate parameters Calendar pageOpenTime = Calendar.getInstance(); pageOpenTime.setTimeInMillis(Long.parseLong(openTime)); timeRange = adjustTimeRange(timeRange, units); List<PageView> pages = new ArrayList<PageView>(); // Perform search Pipe pipe = Gremlin.compile("_().out('owns').out('viewed')"); pipe.setStarts(new SingleIterator<Vertex>(user)); for (Object result : pipe) { if (result instanceof Vertex) { Vertex v = (Vertex) result; PageView pv = new PageView(v); // Add a reference to the parent and successors if edges exist for (Vertex neighbor : v.getVertices(Direction.OUT, "childOf")) { pv.setProperty("parentId", neighbor.getId().toString()); } for (Vertex neighbor : v.getVertices(Direction.OUT, "successorTo")) { pv.setProperty("predecessorId", neighbor.getId().toString()); } pages.add(pv); } } // Turn list into JSON to return String listAsJSON = "["; for(PageView pv : pages) { listAsJSON += pv.toString() + ", "; } listAsJSON = listAsJSON.substring(0, listAsJSON.length()-2); listAsJSON += "]"; // Map to store the results Map<String, String> map = new HashMap<String, String>(); map.put("results", listAsJSON); return ExtensionResponse.ok(map); }
diff --git a/plugins/ASIdiSPIM/src/org/micromanager/asidispim/SpimParamsPanel.java b/plugins/ASIdiSPIM/src/org/micromanager/asidispim/SpimParamsPanel.java index cb2f6761c..ff47222a0 100644 --- a/plugins/ASIdiSPIM/src/org/micromanager/asidispim/SpimParamsPanel.java +++ b/plugins/ASIdiSPIM/src/org/micromanager/asidispim/SpimParamsPanel.java @@ -1,156 +1,156 @@ /////////////////////////////////////////////////////////////////////////////// //FILE: SpimParamsPanel.java //PROJECT: Micro-Manager //SUBSYSTEM: ASIdiSPIM plugin //----------------------------------------------------------------------------- // // AUTHOR: Nico Stuurman, Jon Daniels // // COPYRIGHT: University of California, San Francisco, & ASI, 2013 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.asidispim; import org.micromanager.asidispim.Data.Properties; import org.micromanager.asidispim.Data.Devices; import org.micromanager.asidispim.Utils.DevicesListenerInterface; import org.micromanager.asidispim.Utils.ListeningJPanel; import org.micromanager.asidispim.Utils.PanelUtils; import org.micromanager.utils.ReportingUtils; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JSeparator; import javax.swing.JSpinner; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import net.miginfocom.swing.MigLayout; /** * * @author nico * @author Jon */ @SuppressWarnings("serial") public class SpimParamsPanel extends ListeningJPanel implements DevicesListenerInterface { Devices devices_; Properties props_; public SpimParamsPanel(Devices devices, Properties props) { super(new MigLayout( "", "[right]16[center]16[center]16[center]", "[]12[]")); devices_ = devices; props_ = props; try { PanelUtils pu = new PanelUtils(); JSpinner tmp_jsp; add(new JLabel("Number of sides:"), "split 2"); tmp_jsp = pu.makeSpinnerInteger(1, 2, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SIDES); add(tmp_jsp); add(new JLabel("First side:"), "align right"); String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()}; JComboBox tmp_box = pu.makeDropDownBox(ab, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_FIRSTSIDE); // no listener here add(tmp_box, "wrap"); add(new JLabel("Path A"), "cell 1 2"); add(new JLabel("Path B"), "wrap"); add(new JLabel("Number of repeats:")); tmp_jsp = pu.makeSpinnerInteger(1, 100, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_REPEATS); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Number of slices:")); tmp_jsp = pu.makeSpinnerInteger(1, 100, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SLICES); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Lines scans per slice:")); tmp_jsp = pu.makeSpinnerInteger(1, 1000, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SCANSPERSLICE); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Line scan period (ms):")); tmp_jsp = pu.makeSpinnerInteger(1, 10000, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_LINESCAN_PERIOD); add(tmp_jsp); // TODO remove this if only doing single-sided?? would have to add/remove dynamically which might be a pain tmp_jsp = pu.makeSpinnerInteger(1, 10000, props_, devices_, Devices.Keys.GALVOB, Properties.Keys.SPIM_LINESCAN_PERIOD); add(tmp_jsp, "wrap"); add(new JLabel("Delay before each slice (ms):")); tmp_jsp = pu.makeSpinnerFloat(0, 10000, 0.25, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_DELAY_SLICE); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Delay before each side (ms):")); tmp_jsp = pu.makeSpinnerFloat(0, 10000, 0.25, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_DELAY_SIDE); add(tmp_jsp, "span 2, wrap"); add(new JSeparator(JSeparator.VERTICAL), "growy, cell 3 0 1 9"); JButton buttonStart_ = new JButton("Start!"); buttonStart_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED); - props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED); - props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_RUNNING); + props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED, true); + props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED, true); + props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_RUNNING, true); // TODO generalize this for different ways of running SPIM } }); add(buttonStart_, "cell 4 0, span 2, center, wrap"); JButton buttonSaveSettings_ = new JButton("Save controller settings"); buttonSaveSettings_.setToolTipText("Saves settings to piezo and galvo cards"); buttonSaveSettings_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); - props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); - props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); - props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); + props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); + props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); + props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); + props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); } }); add(buttonSaveSettings_, "cell 4 8, span 2, center, wrap"); } catch (Exception ex) { ReportingUtils.showError("Error creating \"SPIM Params\" tab. Make sure to select devices in \"Devices\" first, then restart plugin"); } } /** * Gets called when this tab gets focus. * Refreshes values from properties. */ @Override public void gotSelected() { props_.callListeners(); } @Override public void devicesChangedAlert() { devices_.callListeners(); } }
false
true
public SpimParamsPanel(Devices devices, Properties props) { super(new MigLayout( "", "[right]16[center]16[center]16[center]", "[]12[]")); devices_ = devices; props_ = props; try { PanelUtils pu = new PanelUtils(); JSpinner tmp_jsp; add(new JLabel("Number of sides:"), "split 2"); tmp_jsp = pu.makeSpinnerInteger(1, 2, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SIDES); add(tmp_jsp); add(new JLabel("First side:"), "align right"); String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()}; JComboBox tmp_box = pu.makeDropDownBox(ab, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_FIRSTSIDE); // no listener here add(tmp_box, "wrap"); add(new JLabel("Path A"), "cell 1 2"); add(new JLabel("Path B"), "wrap"); add(new JLabel("Number of repeats:")); tmp_jsp = pu.makeSpinnerInteger(1, 100, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_REPEATS); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Number of slices:")); tmp_jsp = pu.makeSpinnerInteger(1, 100, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SLICES); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Lines scans per slice:")); tmp_jsp = pu.makeSpinnerInteger(1, 1000, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SCANSPERSLICE); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Line scan period (ms):")); tmp_jsp = pu.makeSpinnerInteger(1, 10000, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_LINESCAN_PERIOD); add(tmp_jsp); // TODO remove this if only doing single-sided?? would have to add/remove dynamically which might be a pain tmp_jsp = pu.makeSpinnerInteger(1, 10000, props_, devices_, Devices.Keys.GALVOB, Properties.Keys.SPIM_LINESCAN_PERIOD); add(tmp_jsp, "wrap"); add(new JLabel("Delay before each slice (ms):")); tmp_jsp = pu.makeSpinnerFloat(0, 10000, 0.25, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_DELAY_SLICE); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Delay before each side (ms):")); tmp_jsp = pu.makeSpinnerFloat(0, 10000, 0.25, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_DELAY_SIDE); add(tmp_jsp, "span 2, wrap"); add(new JSeparator(JSeparator.VERTICAL), "growy, cell 3 0 1 9"); JButton buttonStart_ = new JButton("Start!"); buttonStart_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED); props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED); props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_RUNNING); // TODO generalize this for different ways of running SPIM } }); add(buttonStart_, "cell 4 0, span 2, center, wrap"); JButton buttonSaveSettings_ = new JButton("Save controller settings"); buttonSaveSettings_.setToolTipText("Saves settings to piezo and galvo cards"); buttonSaveSettings_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ); } }); add(buttonSaveSettings_, "cell 4 8, span 2, center, wrap"); } catch (Exception ex) { ReportingUtils.showError("Error creating \"SPIM Params\" tab. Make sure to select devices in \"Devices\" first, then restart plugin"); } }
public SpimParamsPanel(Devices devices, Properties props) { super(new MigLayout( "", "[right]16[center]16[center]16[center]", "[]12[]")); devices_ = devices; props_ = props; try { PanelUtils pu = new PanelUtils(); JSpinner tmp_jsp; add(new JLabel("Number of sides:"), "split 2"); tmp_jsp = pu.makeSpinnerInteger(1, 2, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SIDES); add(tmp_jsp); add(new JLabel("First side:"), "align right"); String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()}; JComboBox tmp_box = pu.makeDropDownBox(ab, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_FIRSTSIDE); // no listener here add(tmp_box, "wrap"); add(new JLabel("Path A"), "cell 1 2"); add(new JLabel("Path B"), "wrap"); add(new JLabel("Number of repeats:")); tmp_jsp = pu.makeSpinnerInteger(1, 100, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_REPEATS); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Number of slices:")); tmp_jsp = pu.makeSpinnerInteger(1, 100, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SLICES); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Lines scans per slice:")); tmp_jsp = pu.makeSpinnerInteger(1, 1000, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_NUM_SCANSPERSLICE); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Line scan period (ms):")); tmp_jsp = pu.makeSpinnerInteger(1, 10000, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_LINESCAN_PERIOD); add(tmp_jsp); // TODO remove this if only doing single-sided?? would have to add/remove dynamically which might be a pain tmp_jsp = pu.makeSpinnerInteger(1, 10000, props_, devices_, Devices.Keys.GALVOB, Properties.Keys.SPIM_LINESCAN_PERIOD); add(tmp_jsp, "wrap"); add(new JLabel("Delay before each slice (ms):")); tmp_jsp = pu.makeSpinnerFloat(0, 10000, 0.25, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_DELAY_SLICE); add(tmp_jsp, "span 2, wrap"); add(new JLabel("Delay before each side (ms):")); tmp_jsp = pu.makeSpinnerFloat(0, 10000, 0.25, props_, devices_, Devices.Keys.GALVOA, Properties.Keys.SPIM_DELAY_SIDE); add(tmp_jsp, "span 2, wrap"); add(new JSeparator(JSeparator.VERTICAL), "growy, cell 3 0 1 9"); JButton buttonStart_ = new JButton("Start!"); buttonStart_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED, true); props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_ARMED, true); props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SPIM_STATE, Properties.Values.SPIM_RUNNING, true); // TODO generalize this for different ways of running SPIM } }); add(buttonStart_, "cell 4 0, span 2, center, wrap"); JButton buttonSaveSettings_ = new JButton("Save controller settings"); buttonSaveSettings_.setToolTipText("Saves settings to piezo and galvo cards"); buttonSaveSettings_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); } }); add(buttonSaveSettings_, "cell 4 8, span 2, center, wrap"); } catch (Exception ex) { ReportingUtils.showError("Error creating \"SPIM Params\" tab. Make sure to select devices in \"Devices\" first, then restart plugin"); } }
diff --git a/jOOQ/src/main/java/org/jooq/impl/RowBetweenCondition.java b/jOOQ/src/main/java/org/jooq/impl/RowBetweenCondition.java index 8031fc5b5..15c4c62a9 100644 --- a/jOOQ/src/main/java/org/jooq/impl/RowBetweenCondition.java +++ b/jOOQ/src/main/java/org/jooq/impl/RowBetweenCondition.java @@ -1,741 +1,741 @@ /** * Copyright (c) 2009-2013, Lukas Eder, [email protected] * All rights reserved. * * This software is licensed to you under the Apache License, Version 2.0 * (the "License"); You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * . Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * . Neither the name "jOOQ" nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.jooq.impl; import static java.util.Arrays.asList; import static org.jooq.impl.Factory.row; import static org.jooq.impl.Factory.vals; import static org.jooq.SQLDialect.ASE; import static org.jooq.SQLDialect.CUBRID; import static org.jooq.SQLDialect.DB2; import static org.jooq.SQLDialect.DERBY; import static org.jooq.SQLDialect.FIREBIRD; import static org.jooq.SQLDialect.H2; import static org.jooq.SQLDialect.MYSQL; import static org.jooq.SQLDialect.ORACLE; import static org.jooq.SQLDialect.SQLITE; import static org.jooq.SQLDialect.SQLSERVER; import static org.jooq.SQLDialect.SYBASE; import java.util.List; import javax.annotation.Generated; import org.jooq.BetweenAndStep1; import org.jooq.BetweenAndStep2; import org.jooq.BetweenAndStep3; import org.jooq.BetweenAndStep4; import org.jooq.BetweenAndStep5; import org.jooq.BetweenAndStep6; import org.jooq.BetweenAndStep7; import org.jooq.BetweenAndStep8; import org.jooq.BetweenAndStep9; import org.jooq.BetweenAndStep10; import org.jooq.BetweenAndStep11; import org.jooq.BetweenAndStep12; import org.jooq.BetweenAndStep13; import org.jooq.BetweenAndStep14; import org.jooq.BetweenAndStep15; import org.jooq.BetweenAndStep16; import org.jooq.BetweenAndStep17; import org.jooq.BetweenAndStep18; import org.jooq.BetweenAndStep19; import org.jooq.BetweenAndStep20; import org.jooq.BetweenAndStep21; import org.jooq.BetweenAndStep22; import org.jooq.BetweenAndStepN; import org.jooq.BindContext; import org.jooq.Condition; import org.jooq.Configuration; import org.jooq.Field; import org.jooq.QueryPartInternal; import org.jooq.Record; import org.jooq.Record1; import org.jooq.Record2; import org.jooq.Record3; import org.jooq.Record4; import org.jooq.Record5; import org.jooq.Record6; import org.jooq.Record7; import org.jooq.Record8; import org.jooq.Record9; import org.jooq.Record10; import org.jooq.Record11; import org.jooq.Record12; import org.jooq.Record13; import org.jooq.Record14; import org.jooq.Record15; import org.jooq.Record16; import org.jooq.Record17; import org.jooq.Record18; import org.jooq.Record19; import org.jooq.Record20; import org.jooq.Record21; import org.jooq.Record22; import org.jooq.RenderContext; import org.jooq.Row; import org.jooq.Row1; import org.jooq.Row2; import org.jooq.Row3; import org.jooq.Row4; import org.jooq.Row5; import org.jooq.Row6; import org.jooq.Row7; import org.jooq.Row8; import org.jooq.Row9; import org.jooq.Row10; import org.jooq.Row11; import org.jooq.Row12; import org.jooq.Row13; import org.jooq.Row14; import org.jooq.Row15; import org.jooq.Row16; import org.jooq.Row17; import org.jooq.Row18; import org.jooq.Row19; import org.jooq.Row20; import org.jooq.Row21; import org.jooq.Row22; import org.jooq.RowN; /** * @author Lukas Eder */ @Generated("This class was generated using jOOQ-tools") @SuppressWarnings({ "rawtypes", "unchecked" }) class RowBetweenCondition<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> extends AbstractCondition implements // This BetweenAndStep implementation implements all types. Type-safety is // being checked through the type-safe API. No need for further checks here BetweenAndStep1<T1>, BetweenAndStep2<T1, T2>, BetweenAndStep3<T1, T2, T3>, BetweenAndStep4<T1, T2, T3, T4>, BetweenAndStep5<T1, T2, T3, T4, T5>, BetweenAndStep6<T1, T2, T3, T4, T5, T6>, BetweenAndStep7<T1, T2, T3, T4, T5, T6, T7>, BetweenAndStep8<T1, T2, T3, T4, T5, T6, T7, T8>, BetweenAndStep9<T1, T2, T3, T4, T5, T6, T7, T8, T9>, BetweenAndStep10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, BetweenAndStep11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, BetweenAndStep13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>, BetweenAndStep14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>, BetweenAndStep15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>, BetweenAndStep16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>, BetweenAndStep17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>, BetweenAndStep18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>, BetweenAndStep19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>, BetweenAndStep20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>, BetweenAndStep21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>, BetweenAndStep22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22>, BetweenAndStepN { private static final long serialVersionUID = -4666251100802237878L; private final boolean symmetric; private final boolean not; private final Row row; private final Row minValue; private Row maxValue; RowBetweenCondition(Row row, Row minValue, boolean not, boolean symmetric) { this.row = row; this.minValue = minValue; this.not = not; this.symmetric = symmetric; } // ------------------------------------------------------------------------ // XXX: BetweenAndStep API // ------------------------------------------------------------------------ @Override public final Condition and(Field<T1> t1) { return and(row(t1)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2) { return and(row(t1, t2)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3) { return and(row(t1, t2, t3)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4) { return and(row(t1, t2, t3, t4)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5) { return and(row(t1, t2, t3, t4, t5)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6) { return and(row(t1, t2, t3, t4, t5, t6)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7) { return and(row(t1, t2, t3, t4, t5, t6, t7)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16, Field<T17> t17) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16, Field<T17> t17, Field<T18> t18) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16, Field<T17> t17, Field<T18> t18, Field<T19> t19) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16, Field<T17> t17, Field<T18> t18, Field<T19> t19, Field<T20> t20) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16, Field<T17> t17, Field<T18> t18, Field<T19> t19, Field<T20> t20, Field<T21> t21) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21)); } @Override public final Condition and(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12, Field<T13> t13, Field<T14> t14, Field<T15> t15, Field<T16> t16, Field<T17> t17, Field<T18> t18, Field<T19> t19, Field<T20> t20, Field<T21> t21, Field<T22> t22) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22)); } @Override public final Condition and(Field<?>... fields) { return and(row(fields)); } @Override public final Condition and(T1 t1) { return and(row(t1)); } @Override public final Condition and(T1 t1, T2 t2) { return and(row(t1, t2)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3) { return and(row(t1, t2, t3)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4) { return and(row(t1, t2, t3, t4)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) { return and(row(t1, t2, t3, t4, t5)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) { return and(row(t1, t2, t3, t4, t5, t6)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7) { return and(row(t1, t2, t3, t4, t5, t6, t7)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19, T20 t20) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19, T20 t20, T21 t21) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21)); } @Override public final Condition and(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19, T20 t20, T21 t21, T22 t22) { return and(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22)); } @Override public final Condition and(Object... values) { return and(row(values)); } @Override public final Condition and(Row1<T1> r) { this.maxValue = r; return this; } @Override public final Condition and(Row2<T1, T2> r) { this.maxValue = r; return this; } @Override public final Condition and(Row3<T1, T2, T3> r) { this.maxValue = r; return this; } @Override public final Condition and(Row4<T1, T2, T3, T4> r) { this.maxValue = r; return this; } @Override public final Condition and(Row5<T1, T2, T3, T4, T5> r) { this.maxValue = r; return this; } @Override public final Condition and(Row6<T1, T2, T3, T4, T5, T6> r) { this.maxValue = r; return this; } @Override public final Condition and(Row7<T1, T2, T3, T4, T5, T6, T7> r) { this.maxValue = r; return this; } @Override public final Condition and(Row8<T1, T2, T3, T4, T5, T6, T7, T8> r) { this.maxValue = r; return this; } @Override public final Condition and(Row9<T1, T2, T3, T4, T5, T6, T7, T8, T9> r) { this.maxValue = r; return this; } @Override public final Condition and(Row10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> r) { this.maxValue = r; return this; } @Override public final Condition and(Row11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> r) { this.maxValue = r; return this; } @Override public final Condition and(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> r) { this.maxValue = r; return this; } @Override public final Condition and(Row13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> r) { this.maxValue = r; return this; } @Override public final Condition and(Row14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> r) { this.maxValue = r; return this; } @Override public final Condition and(Row15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> r) { this.maxValue = r; return this; } @Override public final Condition and(Row16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> r) { this.maxValue = r; return this; } @Override public final Condition and(Row17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> r) { this.maxValue = r; return this; } @Override public final Condition and(Row18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> r) { this.maxValue = r; return this; } @Override public final Condition and(Row19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> r) { this.maxValue = r; return this; } @Override public final Condition and(Row20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> r) { this.maxValue = r; return this; } @Override public final Condition and(Row21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> r) { this.maxValue = r; return this; } @Override public final Condition and(Row22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> r) { this.maxValue = r; return this; } @Override public final Condition and(RowN r) { this.maxValue = r; return this; } @Override public final Condition and(Record1<T1> record) { return and(record.valuesRow()); } @Override public final Condition and(Record2<T1, T2> record) { return and(record.valuesRow()); } @Override public final Condition and(Record3<T1, T2, T3> record) { return and(record.valuesRow()); } @Override public final Condition and(Record4<T1, T2, T3, T4> record) { return and(record.valuesRow()); } @Override public final Condition and(Record5<T1, T2, T3, T4, T5> record) { return and(record.valuesRow()); } @Override public final Condition and(Record6<T1, T2, T3, T4, T5, T6> record) { return and(record.valuesRow()); } @Override public final Condition and(Record7<T1, T2, T3, T4, T5, T6, T7> record) { return and(record.valuesRow()); } @Override public final Condition and(Record8<T1, T2, T3, T4, T5, T6, T7, T8> record) { return and(record.valuesRow()); } @Override public final Condition and(Record9<T1, T2, T3, T4, T5, T6, T7, T8, T9> record) { return and(record.valuesRow()); } @Override public final Condition and(Record10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> record) { return and(record.valuesRow()); } @Override public final Condition and(Record11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> record) { return and(record.valuesRow()); } @Override public final Condition and(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return and(record.valuesRow()); } @Override public final Condition and(Record13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> record) { return and(record.valuesRow()); } @Override public final Condition and(Record14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> record) { return and(record.valuesRow()); } @Override public final Condition and(Record15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> record) { return and(record.valuesRow()); } @Override public final Condition and(Record16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> record) { return and(record.valuesRow()); } @Override public final Condition and(Record17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> record) { return and(record.valuesRow()); } @Override public final Condition and(Record18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> record) { return and(record.valuesRow()); } @Override public final Condition and(Record19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> record) { return and(record.valuesRow()); } @Override public final Condition and(Record20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> record) { return and(record.valuesRow()); } @Override public final Condition and(Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> record) { return and(record.valuesRow()); } @Override public final Condition and(Record22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> record) { return and(record.valuesRow()); } @Override public final Condition and(Record record) { List<Field<?>> f = record.getFields(); RowN r = new RowImpl(vals(record.intoArray(), f.toArray(new Field[f.size()]))); return and(r); } // ------------------------------------------------------------------------ // XXX: QueryPart API // ------------------------------------------------------------------------ @Override public final void bind(BindContext context) { delegate(context).bind(context); } @Override public final void toSQL(RenderContext context) { delegate(context).toSQL(context); } private final QueryPartInternal delegate(Configuration configuration) { // These casts are safe for RowImpl RowN r = (RowN) row; RowN min = (RowN) minValue; RowN max = (RowN) maxValue; // These dialects don't support the SYMMETRIC keyword at all if (symmetric && asList(ASE, CUBRID, DB2, DERBY, FIREBIRD, H2, MYSQL, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { if (not) { return (QueryPartInternal) r.notBetween(min, max).and(r.notBetween(max, min)); } else { return (QueryPartInternal) r.between(min, max).or(r.between(max, min)); } } // These dialects either don't support row value expressions, or they // Can't handle row value expressions with the BETWEEN predicate - else if (row.getDegree() > 1 && asList(CUBRID, DERBY, FIREBIRD, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { + else if (row.getDegree() > 1 && asList(CUBRID, DERBY, FIREBIRD, MYSQL, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { Condition result = r.ge(min).and(r.le(max)); if (not) { result = result.not(); } return (QueryPartInternal) result; } else { return new Native(); } } private class Native extends AbstractQueryPart { /** * Generated UID */ private static final long serialVersionUID = 2915703568738921575L; @Override public final void toSQL(RenderContext context) { context.sql(row) .keyword(not ? " not" : "") .keyword(" between ") .keyword(symmetric ? "symmetric " : "") .sql(minValue) .keyword(" and ") .sql(maxValue); } @Override public final void bind(BindContext context) { context.bind(row).bind(minValue).bind(maxValue); } } }
true
true
private final QueryPartInternal delegate(Configuration configuration) { // These casts are safe for RowImpl RowN r = (RowN) row; RowN min = (RowN) minValue; RowN max = (RowN) maxValue; // These dialects don't support the SYMMETRIC keyword at all if (symmetric && asList(ASE, CUBRID, DB2, DERBY, FIREBIRD, H2, MYSQL, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { if (not) { return (QueryPartInternal) r.notBetween(min, max).and(r.notBetween(max, min)); } else { return (QueryPartInternal) r.between(min, max).or(r.between(max, min)); } } // These dialects either don't support row value expressions, or they // Can't handle row value expressions with the BETWEEN predicate else if (row.getDegree() > 1 && asList(CUBRID, DERBY, FIREBIRD, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { Condition result = r.ge(min).and(r.le(max)); if (not) { result = result.not(); } return (QueryPartInternal) result; } else { return new Native(); } }
private final QueryPartInternal delegate(Configuration configuration) { // These casts are safe for RowImpl RowN r = (RowN) row; RowN min = (RowN) minValue; RowN max = (RowN) maxValue; // These dialects don't support the SYMMETRIC keyword at all if (symmetric && asList(ASE, CUBRID, DB2, DERBY, FIREBIRD, H2, MYSQL, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { if (not) { return (QueryPartInternal) r.notBetween(min, max).and(r.notBetween(max, min)); } else { return (QueryPartInternal) r.between(min, max).or(r.between(max, min)); } } // These dialects either don't support row value expressions, or they // Can't handle row value expressions with the BETWEEN predicate else if (row.getDegree() > 1 && asList(CUBRID, DERBY, FIREBIRD, MYSQL, ORACLE, SQLITE, SQLSERVER, SYBASE).contains(configuration.getDialect())) { Condition result = r.ge(min).and(r.le(max)); if (not) { result = result.not(); } return (QueryPartInternal) result; } else { return new Native(); } }
diff --git a/opentripplanner-updater/src/main/java/org/opentripplanner/updater/bike_rental/BikeRentalUpdater.java b/opentripplanner-updater/src/main/java/org/opentripplanner/updater/bike_rental/BikeRentalUpdater.java index 88fd1dfe5..aee746489 100644 --- a/opentripplanner-updater/src/main/java/org/opentripplanner/updater/bike_rental/BikeRentalUpdater.java +++ b/opentripplanner-updater/src/main/java/org/opentripplanner/updater/bike_rental/BikeRentalUpdater.java @@ -1,142 +1,147 @@ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser 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.opentripplanner.updater.bike_rental; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.PostConstruct; import org.opentripplanner.routing.bike_rental.BikeRentalStation; import org.opentripplanner.routing.bike_rental.BikeRentalStationService; import org.opentripplanner.routing.edgetype.RentABikeOffEdge; import org.opentripplanner.routing.edgetype.RentABikeOnEdge; import org.opentripplanner.routing.edgetype.loader.LinkRequest; import org.opentripplanner.routing.edgetype.loader.NetworkLinkerLibrary; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.services.GraphService; import org.opentripplanner.routing.vertextype.BikeRentalStationVertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; public class BikeRentalUpdater implements Runnable { private static final Logger _log = LoggerFactory.getLogger(BikeRentalUpdater.class); Map<BikeRentalStation, BikeRentalStationVertex> verticesByStation = new HashMap<BikeRentalStation, BikeRentalStationVertex>(); private BikeRentalDataSource source; private Graph graph; private NetworkLinkerLibrary networkLinkerLibrary; private BikeRentalStationService service; private String routerId; private GraphService graphService; private String network = "default"; public void setRouterId(String routerId) { this.routerId = routerId; } public void setNetwork(String network) { this.network = network; } @Autowired public void setBikeRentalDataSource(BikeRentalDataSource source) { this.source = source; } @Autowired public void setGraphService(GraphService graphService) { this.graphService = graphService; } @PostConstruct public void setup() { if (routerId != null) { graph = graphService.getGraph(routerId); } else { graph = graphService.getGraph(); } networkLinkerLibrary = new NetworkLinkerLibrary(graph, Collections.<Class<?>, Object> emptyMap()); service = graph.getService(BikeRentalStationService.class); if (service == null) { service = new BikeRentalStationService(); graph.putService(BikeRentalStationService.class, service); } } public List<BikeRentalStation> getStations() { return source.getStations(); } @Override public void run() { _log.debug("Updating bike rental stations from " + source); if (!source.update()) { _log.debug("No updates"); return; } List<BikeRentalStation> stations = source.getStations(); Set<BikeRentalStation> stationSet = new HashSet<BikeRentalStation>(); Set<String> networks = new HashSet<String>(Arrays.asList(network)); + /* add any new stations and update bike counts for existing stations */ for (BikeRentalStation station : stations) { service.addStation(station); stationSet.add(station); BikeRentalStationVertex vertex = verticesByStation.get(station); if (vertex == null) { vertex = new BikeRentalStationVertex(graph, station); LinkRequest request = networkLinkerLibrary.connectVertexToStreets(vertex); for (Edge e : request.getEdgesAdded()) { graph.addTemporaryEdge(e); } verticesByStation.put(station, vertex); new RentABikeOnEdge(vertex, vertex, networks); new RentABikeOffEdge(vertex, vertex, networks); } else { vertex.setBikesAvailable(station.bikesAvailable); vertex.setSpacesAvailable(station.spacesAvailable); } } - List<BikeRentalStationVertex> toRemove = new ArrayList<BikeRentalStationVertex>(); + /* remove existing stations that were not present in the update */ + List<BikeRentalStation> toRemove = new ArrayList<BikeRentalStation>(); for (Entry<BikeRentalStation, BikeRentalStationVertex> entry : verticesByStation.entrySet()) { BikeRentalStation station = entry.getKey(); if (stationSet.contains(station)) continue; BikeRentalStationVertex vertex = entry.getValue(); if (graph.containsVertex(vertex)) { graph.removeVertexAndEdges(vertex); - toRemove.add(vertex); } + toRemove.add(station); service.removeStation(station); // TODO: need to unsplit any streets that were split } - verticesByStation.keySet().removeAll(toRemove); + for (BikeRentalStation station : toRemove) { + // post-iteration removal to avoid concurrent modification + verticesByStation.remove(station); + } } }
false
true
public void run() { _log.debug("Updating bike rental stations from " + source); if (!source.update()) { _log.debug("No updates"); return; } List<BikeRentalStation> stations = source.getStations(); Set<BikeRentalStation> stationSet = new HashSet<BikeRentalStation>(); Set<String> networks = new HashSet<String>(Arrays.asList(network)); for (BikeRentalStation station : stations) { service.addStation(station); stationSet.add(station); BikeRentalStationVertex vertex = verticesByStation.get(station); if (vertex == null) { vertex = new BikeRentalStationVertex(graph, station); LinkRequest request = networkLinkerLibrary.connectVertexToStreets(vertex); for (Edge e : request.getEdgesAdded()) { graph.addTemporaryEdge(e); } verticesByStation.put(station, vertex); new RentABikeOnEdge(vertex, vertex, networks); new RentABikeOffEdge(vertex, vertex, networks); } else { vertex.setBikesAvailable(station.bikesAvailable); vertex.setSpacesAvailable(station.spacesAvailable); } } List<BikeRentalStationVertex> toRemove = new ArrayList<BikeRentalStationVertex>(); for (Entry<BikeRentalStation, BikeRentalStationVertex> entry : verticesByStation.entrySet()) { BikeRentalStation station = entry.getKey(); if (stationSet.contains(station)) continue; BikeRentalStationVertex vertex = entry.getValue(); if (graph.containsVertex(vertex)) { graph.removeVertexAndEdges(vertex); toRemove.add(vertex); } service.removeStation(station); // TODO: need to unsplit any streets that were split } verticesByStation.keySet().removeAll(toRemove); }
public void run() { _log.debug("Updating bike rental stations from " + source); if (!source.update()) { _log.debug("No updates"); return; } List<BikeRentalStation> stations = source.getStations(); Set<BikeRentalStation> stationSet = new HashSet<BikeRentalStation>(); Set<String> networks = new HashSet<String>(Arrays.asList(network)); /* add any new stations and update bike counts for existing stations */ for (BikeRentalStation station : stations) { service.addStation(station); stationSet.add(station); BikeRentalStationVertex vertex = verticesByStation.get(station); if (vertex == null) { vertex = new BikeRentalStationVertex(graph, station); LinkRequest request = networkLinkerLibrary.connectVertexToStreets(vertex); for (Edge e : request.getEdgesAdded()) { graph.addTemporaryEdge(e); } verticesByStation.put(station, vertex); new RentABikeOnEdge(vertex, vertex, networks); new RentABikeOffEdge(vertex, vertex, networks); } else { vertex.setBikesAvailable(station.bikesAvailable); vertex.setSpacesAvailable(station.spacesAvailable); } } /* remove existing stations that were not present in the update */ List<BikeRentalStation> toRemove = new ArrayList<BikeRentalStation>(); for (Entry<BikeRentalStation, BikeRentalStationVertex> entry : verticesByStation.entrySet()) { BikeRentalStation station = entry.getKey(); if (stationSet.contains(station)) continue; BikeRentalStationVertex vertex = entry.getValue(); if (graph.containsVertex(vertex)) { graph.removeVertexAndEdges(vertex); } toRemove.add(station); service.removeStation(station); // TODO: need to unsplit any streets that were split } for (BikeRentalStation station : toRemove) { // post-iteration removal to avoid concurrent modification verticesByStation.remove(station); } }
diff --git a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java index 984021466..51f5c4620 100644 --- a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java +++ b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java @@ -1,357 +1,357 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ode.axis2.service; import org.apache.ode.store.ProcessStoreImpl; import org.apache.ode.bpel.iapi.ProcessConf; import org.apache.ode.utils.fs.FileUtils; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisOperation; import org.apache.commons.lang.StringUtils; import javax.xml.namespace.QName; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.io.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; /** * handles a set of URLs all starting with /deployment to publish all files in * deployed bundles, services and processes. */ public class DeploymentBrowser { private ProcessStoreImpl _store; private AxisConfiguration _config; private File _appRoot; public DeploymentBrowser(ProcessStoreImpl store, AxisConfiguration config, File appRoot) { _store = store; _config = config; _appRoot = appRoot; } // A fake filter, directly called from the ODEAxisServlet public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String requestURI = request.getRequestURI(); final int deplUri = requestURI.indexOf("/deployment"); if (deplUri > 0) { final String root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + requestURI.substring(0, deplUri); int offset = requestURI.length() > (deplUri + 11) ? 1 : 0; final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/"); if (segments.length == 0 || segments[0].length() == 0) { renderHtml(response, "ODE Deployment Browser", new DocBody() { public void render(Writer out) throws IOException { out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>"); out.write("<p><a href=\"services/\">Process Services</a></p>"); out.write("<p><a href=\"processes/\">Process Definitions</a></p>"); } }); } else if (segments.length > 0) { if ("services".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Services Implemented by Your Processes", new DocBody() { public void render(Writer out) throws IOException { for (Object serviceName : _config.getServices().keySet()) if (!"Version".equals(serviceName)) { AxisService service = _config.getService(serviceName.toString()); // The service can be one of the dynamically registered ODE services, a process // service or an unknown service deployed in the same Axis2 instance. String url = null; if ("DeploymentService".equals(service.getName()) || "InstanceManagement".equals(service.getName()) || "ProcessManagement".equals(service.getName())) url = service.getName(); else if (service.getFileName() != null) { String relative = bundleUrlFor(service.getFileName().getFile()); if (relative != null) url = root + relative; else url = root + "/services/" + service.getName() + "?wsdl"; } out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>"); String axis2wsdl = root + "/processes/" + serviceName + "?wsdl"; - out.write("<ul><li>Axis2 WSDL: " + axis2wsdl + "</a></li>"); - out.write("<ul><li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>"); + out.write("<ul><li>Axis2 WSDL: <a href=\"" + axis2wsdl + "\">" + axis2wsdl + "</a></li>"); + out.write("<li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>"); Iterator iter = service.getOperations(); ArrayList<String> ops = new ArrayList<String>(); while (iter.hasNext()) ops.add(((AxisOperation)iter.next()).getName().getLocalPart()); out.write("<li>Operations: " + StringUtils.join(ops, ", ") + "</li></ul>"); } } }); } else { final String serviceName = requestURI.substring(deplUri + 12 + 9); final AxisService axisService = _config.getService(serviceName); if (axisService != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName)) write(out, new File(_appRoot, "pmapi.wsdl").getPath()); else if (requestURI.indexOf("pmapi.xsd") > 0) write(out, new File(_appRoot, "pmapi.xsd").getPath()); else if ("DeploymentService".equals(serviceName)) write(out, new File(_appRoot, "deploy.wsdl").getPath()); else write(out, axisService.getFileName().getFile()); } }); } else { renderHtml(response, "Service Not Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find service " + serviceName + "</p>"); } }); } } } else if ("processes".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployed Processes", new DocBody() { public void render(Writer out) throws IOException { for (QName process :_store.getProcesses()) { String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); String[] nameVer = process.getLocalPart().split("-"); out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")"); out.write(" - " + process.getNamespaceURI() + "</p>"); } } }); } } else if ("bundles".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployment Bundles", new DocBody() { public void render(Writer out) throws IOException { for (String bundle : _store.getPackages()) out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>"); } }); } else if (segments.length == 2) { renderHtml(response, "Files in Bundle " + segments[1], new DocBody() { public void render(Writer out) throws IOException { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (File file : files) { String relativePath = file.getPath().substring(file.getPath() .indexOf("processes")+10).replaceAll("\\\\", "/"); out.write("<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>"); } } else { out.write("<p>Couldn't find bundle " + segments[1] + "</p>"); } } }); } else if (segments.length > 2) { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (final File file : files) { String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length()); // replace slashes with the correct file separator so the match below is not always false relativePath = relativePath.replace('/', File.separatorChar); if (file.getPath().endsWith(relativePath)) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { write(out, file.getPath()); } }); return true; } } } else { renderHtml(response, "No Bundle Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find bundle " + segments[2] + "</p>"); } }); } } } else if ("getBundleDocs".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getBundleDocsResponse>"); } }); } else if (segments.length == 2) { final String bundleName = segments[1]; final List<QName> processes = _store.listProcesses(bundleName); if (processes != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse><name>"+ bundleName +"</name>"); //final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); //final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString(); for (final QName process: processes) { List<File> files = _store.getProcessConfiguration(process).getFiles(); String pid = _store.getProcessConfiguration(process).getProcessId().toString(); out.write("<process><pid>"+pid+"</pid>"); for (final File file : files) { if (file.getPath().endsWith(".wsdl")) { String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1).replace(File.separatorChar, '/'); out.write("<wsdl>"+ relativePath + "</wsdl>"); } if (file.getPath().endsWith(".bpel")) { String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1).replace(File.separatorChar, '/'); out.write("<bpel>"+ relativePath + "</bpel>"); } } out.write("</process>"); } out.write("</getBundleDocsResponse>"); } }); } } } else if ("getProcessDefinition".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException{ out.write("<getProcessDefinitionResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getProcessDefinitionResponse>"); } }); } else if (segments.length == 2) { String processName = segments[1]; for (QName process :_store.getProcesses()) { String[] nameVer = process.getLocalPart().split("-"); if(processName.equals(nameVer[0])) { final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getProcessDefinition>"); out.write("<url>"+ url +"</url>"); out.write("</getProcessDefinition>"); } }); } } } } } return true; } return false; } static interface DocBody { void render(Writer out) throws IOException; } private void renderHtml(HttpServletResponse response, String title, DocBody docBody) throws IOException { response.setContentType("text/html"); Writer out = response.getWriter(); out.write("<html><header><style type=\"text/css\">" + CSS + "</style></header><body>\n"); out.write("<h2>" + title + "</h2><p/>\n"); docBody.render(out); out.write("</body></html>"); } private void renderXml(HttpServletResponse response, DocBody docBody) throws IOException { response.setContentType("application/xml; charset=utf-8"); //response.setContentType("application/xml"); //response.setCharacterEncoding("UTF-8"); Writer out = response.getWriter(); docBody.render(out); } private void write(Writer out, String filePath) throws IOException { BufferedReader wsdlReader = new BufferedReader(new FileReader(filePath)); String line; while((line = wsdlReader.readLine()) != null) out.write(line + "\n"); wsdlReader.close(); } private String bundleUrlFor(String docFile) { if (docFile.indexOf("processes") >= 0) docFile = docFile.substring(docFile.indexOf("processes")+10); List<File> files = FileUtils.directoryEntriesInPath(_store.getDeployDir(), null); for (final File bundleFile : files) { if (bundleFile.getPath().replaceAll("\\\\", "/").endsWith(docFile)) return "/deployment/bundles/" + bundleFile.getPath() .substring(_store.getDeployDir().getPath().length() + 1).replaceAll("\\\\", "/"); } return null; } private static final String CSS = "body {\n" + " font: 75% Verdana, Helvetica, Arial, sans-serif;\n" + " background: White;\n" + " color: Black;\n" + " margin: 1em;\n" + " padding: 1em;\n" + "}\n" + "\n" + "h1, h2, h3, h4, h5, h6 {\n" + " color: Black;\n" + " clear: left;\n" + " font: 100% Verdana, Helvetica, Arial, sans-serif;\n" + " margin: 0;\n" + " padding-left: 0.5em;\n" + "} \n" + "\n" + "h1 {\n" + " font-size: 150%;\n" + " border-bottom: none;\n" + " text-align: right;\n" + " border-bottom: 1px solid Gray;\n" + "}\n" + " \n" + "h2 {\n" + " font-size: 130%;\n" + " border-bottom: 1px solid Gray;\n" + "}\n" + "\n" + "h3 {\n" + " font-size: 120%;\n" + " padding-left: 1.0em;\n" + " border-bottom: 1px solid Gray;\n" + "}\n" + "\n" + "h4 {\n" + " font-size: 110%;\n" + " padding-left: 1.5em;\n" + " border-bottom: 1px solid Gray;\n" + "}\n" + "\n" + "p {\n" + " text-align: justify;\n" + " line-height: 1.5em;\n" + " padding-left: 1.5em;\n" + "}\n" + "\n" + "a {\n" + " text-decoration: underline;\n" + " color: Black;\n" + "}"; }
true
true
public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String requestURI = request.getRequestURI(); final int deplUri = requestURI.indexOf("/deployment"); if (deplUri > 0) { final String root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + requestURI.substring(0, deplUri); int offset = requestURI.length() > (deplUri + 11) ? 1 : 0; final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/"); if (segments.length == 0 || segments[0].length() == 0) { renderHtml(response, "ODE Deployment Browser", new DocBody() { public void render(Writer out) throws IOException { out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>"); out.write("<p><a href=\"services/\">Process Services</a></p>"); out.write("<p><a href=\"processes/\">Process Definitions</a></p>"); } }); } else if (segments.length > 0) { if ("services".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Services Implemented by Your Processes", new DocBody() { public void render(Writer out) throws IOException { for (Object serviceName : _config.getServices().keySet()) if (!"Version".equals(serviceName)) { AxisService service = _config.getService(serviceName.toString()); // The service can be one of the dynamically registered ODE services, a process // service or an unknown service deployed in the same Axis2 instance. String url = null; if ("DeploymentService".equals(service.getName()) || "InstanceManagement".equals(service.getName()) || "ProcessManagement".equals(service.getName())) url = service.getName(); else if (service.getFileName() != null) { String relative = bundleUrlFor(service.getFileName().getFile()); if (relative != null) url = root + relative; else url = root + "/services/" + service.getName() + "?wsdl"; } out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>"); String axis2wsdl = root + "/processes/" + serviceName + "?wsdl"; out.write("<ul><li>Axis2 WSDL: " + axis2wsdl + "</a></li>"); out.write("<ul><li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>"); Iterator iter = service.getOperations(); ArrayList<String> ops = new ArrayList<String>(); while (iter.hasNext()) ops.add(((AxisOperation)iter.next()).getName().getLocalPart()); out.write("<li>Operations: " + StringUtils.join(ops, ", ") + "</li></ul>"); } } }); } else { final String serviceName = requestURI.substring(deplUri + 12 + 9); final AxisService axisService = _config.getService(serviceName); if (axisService != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName)) write(out, new File(_appRoot, "pmapi.wsdl").getPath()); else if (requestURI.indexOf("pmapi.xsd") > 0) write(out, new File(_appRoot, "pmapi.xsd").getPath()); else if ("DeploymentService".equals(serviceName)) write(out, new File(_appRoot, "deploy.wsdl").getPath()); else write(out, axisService.getFileName().getFile()); } }); } else { renderHtml(response, "Service Not Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find service " + serviceName + "</p>"); } }); } } } else if ("processes".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployed Processes", new DocBody() { public void render(Writer out) throws IOException { for (QName process :_store.getProcesses()) { String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); String[] nameVer = process.getLocalPart().split("-"); out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")"); out.write(" - " + process.getNamespaceURI() + "</p>"); } } }); } } else if ("bundles".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployment Bundles", new DocBody() { public void render(Writer out) throws IOException { for (String bundle : _store.getPackages()) out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>"); } }); } else if (segments.length == 2) { renderHtml(response, "Files in Bundle " + segments[1], new DocBody() { public void render(Writer out) throws IOException { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (File file : files) { String relativePath = file.getPath().substring(file.getPath() .indexOf("processes")+10).replaceAll("\\\\", "/"); out.write("<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>"); } } else { out.write("<p>Couldn't find bundle " + segments[1] + "</p>"); } } }); } else if (segments.length > 2) { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (final File file : files) { String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length()); // replace slashes with the correct file separator so the match below is not always false relativePath = relativePath.replace('/', File.separatorChar); if (file.getPath().endsWith(relativePath)) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { write(out, file.getPath()); } }); return true; } } } else { renderHtml(response, "No Bundle Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find bundle " + segments[2] + "</p>"); } }); } } } else if ("getBundleDocs".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getBundleDocsResponse>"); } }); } else if (segments.length == 2) { final String bundleName = segments[1]; final List<QName> processes = _store.listProcesses(bundleName); if (processes != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse><name>"+ bundleName +"</name>"); //final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); //final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString(); for (final QName process: processes) { List<File> files = _store.getProcessConfiguration(process).getFiles(); String pid = _store.getProcessConfiguration(process).getProcessId().toString(); out.write("<process><pid>"+pid+"</pid>"); for (final File file : files) { if (file.getPath().endsWith(".wsdl")) { String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1).replace(File.separatorChar, '/'); out.write("<wsdl>"+ relativePath + "</wsdl>"); } if (file.getPath().endsWith(".bpel")) { String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1).replace(File.separatorChar, '/'); out.write("<bpel>"+ relativePath + "</bpel>"); } } out.write("</process>"); } out.write("</getBundleDocsResponse>"); } }); } } } else if ("getProcessDefinition".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException{ out.write("<getProcessDefinitionResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getProcessDefinitionResponse>"); } }); } else if (segments.length == 2) { String processName = segments[1]; for (QName process :_store.getProcesses()) { String[] nameVer = process.getLocalPart().split("-"); if(processName.equals(nameVer[0])) { final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getProcessDefinition>"); out.write("<url>"+ url +"</url>"); out.write("</getProcessDefinition>"); } }); } } } } } return true; } return false; }
public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String requestURI = request.getRequestURI(); final int deplUri = requestURI.indexOf("/deployment"); if (deplUri > 0) { final String root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + requestURI.substring(0, deplUri); int offset = requestURI.length() > (deplUri + 11) ? 1 : 0; final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/"); if (segments.length == 0 || segments[0].length() == 0) { renderHtml(response, "ODE Deployment Browser", new DocBody() { public void render(Writer out) throws IOException { out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>"); out.write("<p><a href=\"services/\">Process Services</a></p>"); out.write("<p><a href=\"processes/\">Process Definitions</a></p>"); } }); } else if (segments.length > 0) { if ("services".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Services Implemented by Your Processes", new DocBody() { public void render(Writer out) throws IOException { for (Object serviceName : _config.getServices().keySet()) if (!"Version".equals(serviceName)) { AxisService service = _config.getService(serviceName.toString()); // The service can be one of the dynamically registered ODE services, a process // service or an unknown service deployed in the same Axis2 instance. String url = null; if ("DeploymentService".equals(service.getName()) || "InstanceManagement".equals(service.getName()) || "ProcessManagement".equals(service.getName())) url = service.getName(); else if (service.getFileName() != null) { String relative = bundleUrlFor(service.getFileName().getFile()); if (relative != null) url = root + relative; else url = root + "/services/" + service.getName() + "?wsdl"; } out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>"); String axis2wsdl = root + "/processes/" + serviceName + "?wsdl"; out.write("<ul><li>Axis2 WSDL: <a href=\"" + axis2wsdl + "\">" + axis2wsdl + "</a></li>"); out.write("<li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>"); Iterator iter = service.getOperations(); ArrayList<String> ops = new ArrayList<String>(); while (iter.hasNext()) ops.add(((AxisOperation)iter.next()).getName().getLocalPart()); out.write("<li>Operations: " + StringUtils.join(ops, ", ") + "</li></ul>"); } } }); } else { final String serviceName = requestURI.substring(deplUri + 12 + 9); final AxisService axisService = _config.getService(serviceName); if (axisService != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName)) write(out, new File(_appRoot, "pmapi.wsdl").getPath()); else if (requestURI.indexOf("pmapi.xsd") > 0) write(out, new File(_appRoot, "pmapi.xsd").getPath()); else if ("DeploymentService".equals(serviceName)) write(out, new File(_appRoot, "deploy.wsdl").getPath()); else write(out, axisService.getFileName().getFile()); } }); } else { renderHtml(response, "Service Not Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find service " + serviceName + "</p>"); } }); } } } else if ("processes".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployed Processes", new DocBody() { public void render(Writer out) throws IOException { for (QName process :_store.getProcesses()) { String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); String[] nameVer = process.getLocalPart().split("-"); out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")"); out.write(" - " + process.getNamespaceURI() + "</p>"); } } }); } } else if ("bundles".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployment Bundles", new DocBody() { public void render(Writer out) throws IOException { for (String bundle : _store.getPackages()) out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>"); } }); } else if (segments.length == 2) { renderHtml(response, "Files in Bundle " + segments[1], new DocBody() { public void render(Writer out) throws IOException { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (File file : files) { String relativePath = file.getPath().substring(file.getPath() .indexOf("processes")+10).replaceAll("\\\\", "/"); out.write("<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>"); } } else { out.write("<p>Couldn't find bundle " + segments[1] + "</p>"); } } }); } else if (segments.length > 2) { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (final File file : files) { String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length()); // replace slashes with the correct file separator so the match below is not always false relativePath = relativePath.replace('/', File.separatorChar); if (file.getPath().endsWith(relativePath)) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { write(out, file.getPath()); } }); return true; } } } else { renderHtml(response, "No Bundle Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find bundle " + segments[2] + "</p>"); } }); } } } else if ("getBundleDocs".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getBundleDocsResponse>"); } }); } else if (segments.length == 2) { final String bundleName = segments[1]; final List<QName> processes = _store.listProcesses(bundleName); if (processes != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse><name>"+ bundleName +"</name>"); //final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); //final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString(); for (final QName process: processes) { List<File> files = _store.getProcessConfiguration(process).getFiles(); String pid = _store.getProcessConfiguration(process).getProcessId().toString(); out.write("<process><pid>"+pid+"</pid>"); for (final File file : files) { if (file.getPath().endsWith(".wsdl")) { String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1).replace(File.separatorChar, '/'); out.write("<wsdl>"+ relativePath + "</wsdl>"); } if (file.getPath().endsWith(".bpel")) { String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1).replace(File.separatorChar, '/'); out.write("<bpel>"+ relativePath + "</bpel>"); } } out.write("</process>"); } out.write("</getBundleDocsResponse>"); } }); } } } else if ("getProcessDefinition".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException{ out.write("<getProcessDefinitionResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getProcessDefinitionResponse>"); } }); } else if (segments.length == 2) { String processName = segments[1]; for (QName process :_store.getProcesses()) { String[] nameVer = process.getLocalPart().split("-"); if(processName.equals(nameVer[0])) { final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getProcessDefinition>"); out.write("<url>"+ url +"</url>"); out.write("</getProcessDefinition>"); } }); } } } } } return true; } return false; }
diff --git a/CLIENT/src/com/kaist/crescendo/manager/UpdateManager.java b/CLIENT/src/com/kaist/crescendo/manager/UpdateManager.java index 60b1d1e..a98de9d 100644 --- a/CLIENT/src/com/kaist/crescendo/manager/UpdateManager.java +++ b/CLIENT/src/com/kaist/crescendo/manager/UpdateManager.java @@ -1,732 +1,733 @@ package com.kaist.crescendo.manager; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.kaist.crescendo.R; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.kaist.crescendo.data.FriendData; import com.kaist.crescendo.data.HistoryData; import com.kaist.crescendo.data.PlanData; import com.kaist.crescendo.data.UserData; import com.kaist.crescendo.utils.MyStaticValue; public class UpdateManager implements UpdateManagerInterface { private String asyncTaskResult; private int asyncTaskState; private Context mContext; private final String TAG = "UpdateManager"; private void showToastPopup(int result) { switch(result) { case MsgInfo.STATUS_OK: //Toast.makeText(mContext, mContext.getString(R.string.str_success), Toast.LENGTH_LONG).show(); break; case MsgInfo.STATUS_DUPLICATED_USERID: Toast.makeText(mContext, mContext.getString(R.string.str_duplicated_user), Toast.LENGTH_LONG).show(); break; case MsgInfo.STATUS_INVALID_PASSWORD: Toast.makeText(mContext, mContext.getString(R.string.str_invalid_password), Toast.LENGTH_LONG).show(); break; case MsgInfo.STATUS_UNREGISTERED_USERID: Toast.makeText(mContext, mContext.getString(R.string.str_unresigered_user), Toast.LENGTH_LONG).show(); break; default: break; } } private void makeMsgHeader(JSONObject msg, int msgId) { try { msg.put(MsgInfo.MSGID_LABEL, msgId); msg.put(MsgInfo.MSGDIR_LABEL, MsgInfo.MSG_SEND_VALUE); msg.put(MsgInfo.MSGLEN_LABLE, 0); msg.put(MsgInfo.MSGRET_LABEL, MsgInfo.STATUS_OK); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void makeMsgBody(JSONObject msg, Object body) { int msgId = 0; UserData uData = null; PlanData pData = null; JSONArray HisArray = null; JSONObject temp_body = new JSONObject(); try { msgId = msg.getInt(MsgInfo.MSGID_LABEL); } catch (Exception e) { // TODO: handle exception } try { temp_body.put(MsgInfo.DEF_USERID_LABEL, MyStaticValue.myId); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } switch(msgId) { case MsgInfo.REGISTER_USER: uData = (UserData)body; try { temp_body.put(MsgInfo.USERID_LABEL, uData.id); temp_body.put(MsgInfo.PASSWORD_LABEL, uData.password); temp_body.put(MsgInfo.PHONENUM_LABEL, uData.phoneNum); temp_body.put(MsgInfo.BIRTHDAY_LABEL, uData.birthDay); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.SYS_LOGIN: uData = (UserData)body; try { temp_body.put(MsgInfo.USERID_LABEL, uData.id); temp_body.put(MsgInfo.PASSWORD_LABEL, uData.password); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.ADD_NEW_PLAN: case MsgInfo.UPDATE_PLAN: pData = (PlanData)body; try { temp_body.put(MsgInfo.PLAN_UID_LABEL, pData.uId); temp_body.put(MsgInfo.PLAN_TYPE_LABEL, pData.type); temp_body.put(MsgInfo.PLAN_TITLE_LABEL, pData.title); temp_body.put(MsgInfo.PLAN_DAYOFWEEK_LABEL, pData.dayOfWeek); temp_body.put(MsgInfo.PLAN_SDATE_LABEL, pData.start); temp_body.put(MsgInfo.PLAN_EDATE_LABEL, pData.end); + temp_body.put(MsgInfo.PLAN_ALARMTIME_LABEL, pData.alarm); temp_body.put(MsgInfo.PLAN_INIT_VAL_LABEL, pData.initValue); temp_body.put(MsgInfo.PLAN_TARGET_VAL_LABEL, pData.targetValue); temp_body.put(MsgInfo.PLAN_IS_SELECTED_LABEL, pData.isSelected); HisArray = new JSONArray(); for(int i = 0 ; i < pData.hItem.size() ; i++) { //add plan history data using JSONArray JSONObject hData = new JSONObject(); hData.put(MsgInfo.PLAN_HISDATE_LABEL, ((HistoryData)pData.hItem.get(i)).date); hData.put(MsgInfo.PLAN_HISVAL_LABEL, ((HistoryData)pData.hItem.get(i)).value); HisArray.put(i, hData); } if(HisArray != null) { temp_body.put(MsgInfo.PLAN_HISTORY_LABEL, HisArray); } msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.GET_PLAN: case MsgInfo.GET_FRIEND: try { msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: break; } } private void makeMsgBody(JSONObject msg, String curPassword, String newPassword) { int msgId = 0; JSONObject temp_body = new JSONObject(); try { msgId = msg.getInt(MsgInfo.MSGID_LABEL); } catch (Exception e) { // TODO: handle exception } try { temp_body.put(MsgInfo.DEF_USERID_LABEL, MyStaticValue.myId); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(msgId == MsgInfo.CHANGE_PASSWORD) { try { temp_body.put(MsgInfo.PASSWORD_LABEL, curPassword); temp_body.put(MsgInfo.NEWPASSWORD_LABEL, newPassword); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void makeMsgBody(JSONObject msg, int planId) { int msgId = 0; JSONObject temp_body = new JSONObject(); try { msgId = msg.getInt(MsgInfo.MSGID_LABEL); } catch (Exception e) { // TODO: handle exception } try { temp_body.put(MsgInfo.DEF_USERID_LABEL, MyStaticValue.myId); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(msgId == MsgInfo.DEL_PLAN) { try { temp_body.put(MsgInfo.PLAN_UID_LABEL, planId); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void makeMsgBody(JSONObject msg, String userId) { int msgId = 0; JSONObject temp_body = new JSONObject(); try { msgId = msg.getInt(MsgInfo.MSGID_LABEL); } catch (Exception e) { // TODO: handle exception } try { temp_body.put(MsgInfo.DEF_USERID_LABEL, MyStaticValue.myId); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(msgId == MsgInfo.DEL_FRIEND || msgId == MsgInfo.SEL_AVATA_FRIEND) { try { temp_body.put(MsgInfo.USERID_LABEL, userId); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void makeRetMessage(Object retMsg, JSONObject receivedObj) { //convert receivedObj to retMsg int msgId = 0; int itemCnt = 0; JSONObject jsonObjcect = null; JSONArray jsonArray = null; JSONArray jsonArray2 = null; try { msgId = receivedObj.getInt(MsgInfo.MSGID_LABEL); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(msgId == MsgInfo.GET_PLAN) { ArrayList<PlanData> planArrayList = (ArrayList<PlanData>) retMsg; try { jsonArray = receivedObj.getJSONArray(MsgInfo.MSGBODY_LABEL); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(jsonArray != null) { for(int i = 0; i < jsonArray.length() ; i++) { String startDay = null; String endDay = null; String title = null; String alarm = null; int type = 0; boolean isSel = false; double initVal = 0.0f; double tarVal = 0.0f; int dayOfWeek = 0; int uId = 0; JSONObject obj = null; try { obj = jsonArray.getJSONObject(i); uId = obj.getInt(MsgInfo.PLAN_UID_LABEL); title = obj.getString(MsgInfo.PLAN_TITLE_LABEL); type = obj.getInt(MsgInfo.PLAN_TYPE_LABEL); startDay = obj.getString(MsgInfo.PLAN_SDATE_LABEL); alarm = obj.getString(MsgInfo.PLAN_ALARMTIME_LABEL); endDay = obj.getString(MsgInfo.PLAN_EDATE_LABEL); initVal = obj.getDouble(MsgInfo.PLAN_INIT_VAL_LABEL); tarVal = obj.getDouble(MsgInfo.PLAN_TARGET_VAL_LABEL); isSel = obj.getBoolean(MsgInfo.PLAN_IS_SELECTED_LABEL); dayOfWeek = obj.getInt(MsgInfo.PLAN_DAYOFWEEK_LABEL); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } PlanData plan = new PlanData(type, title, startDay, endDay, alarm, dayOfWeek, initVal, tarVal); plan.uId = uId; plan.isSelected = isSel; try { jsonArray2 = obj.getJSONArray(MsgInfo.PLAN_HISTORY_LABEL); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(jsonArray2 != null) { for(int j = 0 ; j < jsonArray2.length() ; j++) { JSONObject obj2; String date = null; int value = 0; try { obj2 = jsonArray2.getJSONObject(j); date = obj2.getString(MsgInfo.PLAN_HISDATE_LABEL); value = obj2.getInt(MsgInfo.PLAN_HISVAL_LABEL); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } HistoryData hisData = new HistoryData(date, value); plan.hItem.add(hisData); } } planArrayList.add(plan); } } } } public int register(Context context, UserData uData) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.REGISTER_USER); makeMsgBody(msg, uData); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } public int login(Context context, UserData uData) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.SYS_LOGIN); makeMsgBody(msg, uData); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } @Override public int addNewPlan(Context context, PlanData plan) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.ADD_NEW_PLAN); makeMsgBody(msg, plan); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } @Override public int updatePlan(Context context, PlanData plan) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.UPDATE_PLAN); makeMsgBody(msg, plan); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } @Override public int deletePlan(Context context, int plan_uId) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.DEL_PLAN); makeMsgBody(msg, plan_uId); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } @Override public int getPlanList(Context context, ArrayList<PlanData> planArrayList) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.GET_PLAN); makeMsgBody(msg, planArrayList); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); makeRetMessage(planArrayList, revMsg); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } @Override public int getFriend(Context context, ArrayList<FriendData> friendArrayList) { // TODO Auto-generated method stub return 0; } @Override public int getCandidate(Context context, ArrayList<FriendData> candidateArrayList) { // TODO Auto-generated method stub return 0; } @Override public int addNewFriend(Context context, ArrayList<FriendData> friendArrayList) { // TODO Auto-generated method stub //make temporal code for testing return 0; } @Override public int delFriend(Context context, String friendUserId) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.DEL_FRIEND); makeMsgBody(msg, friendUserId); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } @Override public int setAvataFriend(Context context, String friendUserId) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.SEL_AVATA_FRIEND); makeMsgBody(msg, friendUserId); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } public int changePassword(Context context, String curPassword, String newPassword) { int result = MsgInfo.STATUS_OK; JSONObject msg = new JSONObject(); JSONObject revMsg = null; mContext = context; makeMsgHeader(msg, MsgInfo.CHANGE_PASSWORD); makeMsgBody(msg, curPassword, newPassword); new SendAsyncTask().execute(msg); while(asyncTaskState == -1) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } try { revMsg = new JSONObject(asyncTaskResult); result = revMsg.getInt(MsgInfo.MSGRET_LABEL); } catch (Exception e) { // TODO: handle exception } showToastPopup(result); return result; } public class SendAsyncTask extends AsyncTask<JSONObject, Integer, Integer>{ private ProgressDialog dialog; @Override protected void onPreExecute() { asyncTaskState = -1; dialog = new ProgressDialog(mContext); dialog.setTitle("ó����"); dialog.setMessage("��ø� ��ٷ��ּ���."); dialog.setIndeterminate(true); dialog.setCancelable(true); dialog.show(); super.onPreExecute(); } @Override protected void onProgressUpdate(Integer... progress) { } @Override protected void onPostExecute(Integer result) { dialog.dismiss(); super.onPostExecute(result); } @Override protected Integer doInBackground(JSONObject... params) { ComManager manager = new ComManager(); int result = MsgInfo.STATUS_OK; asyncTaskResult = manager.processMsg(params[0]); Log.v(TAG, asyncTaskResult); dialog.dismiss(); asyncTaskState = 0; return result; } } }
true
true
private void makeMsgBody(JSONObject msg, Object body) { int msgId = 0; UserData uData = null; PlanData pData = null; JSONArray HisArray = null; JSONObject temp_body = new JSONObject(); try { msgId = msg.getInt(MsgInfo.MSGID_LABEL); } catch (Exception e) { // TODO: handle exception } try { temp_body.put(MsgInfo.DEF_USERID_LABEL, MyStaticValue.myId); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } switch(msgId) { case MsgInfo.REGISTER_USER: uData = (UserData)body; try { temp_body.put(MsgInfo.USERID_LABEL, uData.id); temp_body.put(MsgInfo.PASSWORD_LABEL, uData.password); temp_body.put(MsgInfo.PHONENUM_LABEL, uData.phoneNum); temp_body.put(MsgInfo.BIRTHDAY_LABEL, uData.birthDay); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.SYS_LOGIN: uData = (UserData)body; try { temp_body.put(MsgInfo.USERID_LABEL, uData.id); temp_body.put(MsgInfo.PASSWORD_LABEL, uData.password); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.ADD_NEW_PLAN: case MsgInfo.UPDATE_PLAN: pData = (PlanData)body; try { temp_body.put(MsgInfo.PLAN_UID_LABEL, pData.uId); temp_body.put(MsgInfo.PLAN_TYPE_LABEL, pData.type); temp_body.put(MsgInfo.PLAN_TITLE_LABEL, pData.title); temp_body.put(MsgInfo.PLAN_DAYOFWEEK_LABEL, pData.dayOfWeek); temp_body.put(MsgInfo.PLAN_SDATE_LABEL, pData.start); temp_body.put(MsgInfo.PLAN_EDATE_LABEL, pData.end); temp_body.put(MsgInfo.PLAN_INIT_VAL_LABEL, pData.initValue); temp_body.put(MsgInfo.PLAN_TARGET_VAL_LABEL, pData.targetValue); temp_body.put(MsgInfo.PLAN_IS_SELECTED_LABEL, pData.isSelected); HisArray = new JSONArray(); for(int i = 0 ; i < pData.hItem.size() ; i++) { //add plan history data using JSONArray JSONObject hData = new JSONObject(); hData.put(MsgInfo.PLAN_HISDATE_LABEL, ((HistoryData)pData.hItem.get(i)).date); hData.put(MsgInfo.PLAN_HISVAL_LABEL, ((HistoryData)pData.hItem.get(i)).value); HisArray.put(i, hData); } if(HisArray != null) { temp_body.put(MsgInfo.PLAN_HISTORY_LABEL, HisArray); } msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.GET_PLAN: case MsgInfo.GET_FRIEND: try { msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: break; } }
private void makeMsgBody(JSONObject msg, Object body) { int msgId = 0; UserData uData = null; PlanData pData = null; JSONArray HisArray = null; JSONObject temp_body = new JSONObject(); try { msgId = msg.getInt(MsgInfo.MSGID_LABEL); } catch (Exception e) { // TODO: handle exception } try { temp_body.put(MsgInfo.DEF_USERID_LABEL, MyStaticValue.myId); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } switch(msgId) { case MsgInfo.REGISTER_USER: uData = (UserData)body; try { temp_body.put(MsgInfo.USERID_LABEL, uData.id); temp_body.put(MsgInfo.PASSWORD_LABEL, uData.password); temp_body.put(MsgInfo.PHONENUM_LABEL, uData.phoneNum); temp_body.put(MsgInfo.BIRTHDAY_LABEL, uData.birthDay); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.SYS_LOGIN: uData = (UserData)body; try { temp_body.put(MsgInfo.USERID_LABEL, uData.id); temp_body.put(MsgInfo.PASSWORD_LABEL, uData.password); msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.ADD_NEW_PLAN: case MsgInfo.UPDATE_PLAN: pData = (PlanData)body; try { temp_body.put(MsgInfo.PLAN_UID_LABEL, pData.uId); temp_body.put(MsgInfo.PLAN_TYPE_LABEL, pData.type); temp_body.put(MsgInfo.PLAN_TITLE_LABEL, pData.title); temp_body.put(MsgInfo.PLAN_DAYOFWEEK_LABEL, pData.dayOfWeek); temp_body.put(MsgInfo.PLAN_SDATE_LABEL, pData.start); temp_body.put(MsgInfo.PLAN_EDATE_LABEL, pData.end); temp_body.put(MsgInfo.PLAN_ALARMTIME_LABEL, pData.alarm); temp_body.put(MsgInfo.PLAN_INIT_VAL_LABEL, pData.initValue); temp_body.put(MsgInfo.PLAN_TARGET_VAL_LABEL, pData.targetValue); temp_body.put(MsgInfo.PLAN_IS_SELECTED_LABEL, pData.isSelected); HisArray = new JSONArray(); for(int i = 0 ; i < pData.hItem.size() ; i++) { //add plan history data using JSONArray JSONObject hData = new JSONObject(); hData.put(MsgInfo.PLAN_HISDATE_LABEL, ((HistoryData)pData.hItem.get(i)).date); hData.put(MsgInfo.PLAN_HISVAL_LABEL, ((HistoryData)pData.hItem.get(i)).value); HisArray.put(i, hData); } if(HisArray != null) { temp_body.put(MsgInfo.PLAN_HISTORY_LABEL, HisArray); } msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (Exception e) { // TODO: handle exception } break; case MsgInfo.GET_PLAN: case MsgInfo.GET_FRIEND: try { msg.put(MsgInfo.MSGBODY_LABEL, temp_body); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: break; } }
diff --git a/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchView.java b/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchView.java index 43df50598..4bca665db 100644 --- a/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchView.java +++ b/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchView.java @@ -1,979 +1,979 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.schemaeditor.view.views; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.apache.directory.shared.ldap.schema.SchemaObject; import org.apache.directory.studio.schemaeditor.Activator; import org.apache.directory.studio.schemaeditor.PluginConstants; import org.apache.directory.studio.schemaeditor.PluginUtils; import org.apache.directory.studio.schemaeditor.controller.SchemaHandler; import org.apache.directory.studio.schemaeditor.controller.SearchViewController; import org.apache.directory.studio.schemaeditor.model.AttributeTypeImpl; import org.apache.directory.studio.schemaeditor.model.ObjectClassImpl; import org.apache.directory.studio.schemaeditor.view.ViewUtils; import org.apache.directory.studio.schemaeditor.view.editors.attributetype.AttributeTypeEditor; import org.apache.directory.studio.schemaeditor.view.editors.attributetype.AttributeTypeEditorInput; import org.apache.directory.studio.schemaeditor.view.editors.objectclass.ObjectClassEditor; import org.apache.directory.studio.schemaeditor.view.editors.objectclass.ObjectClassEditorInput; import org.apache.directory.studio.schemaeditor.view.search.SearchPage; import org.apache.directory.studio.schemaeditor.view.search.SearchPage.SearchInEnum; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.plugin.AbstractUIPlugin; /** * This class represents the Search View. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class SearchView extends ViewPart { /** The view's ID */ public static final String ID = Activator.PLUGIN_ID + ".view.SearchView"; //$NON-NLS-1$ /** The current Search String */ private String searchString; // UI fields private Text searchField; private Button searchButton; private Label searchResultsLabel; private Table resultsTable; private TableViewer resultsTableViewer; private Composite searchFieldComposite; private Composite searchFieldInnerComposite; private Label separatorLabel; /** The parent composite */ private Composite parent; /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl( Composite parent ) { // Help Context for Dynamic Help PlatformUI.getWorkbench().getHelpSystem().setHelp( parent, Activator.PLUGIN_ID + "." + "search_view" ); this.parent = parent; GridLayout gridLayout = new GridLayout(); gridLayout.horizontalSpacing = 0; gridLayout.marginBottom = 0; gridLayout.marginHeight = 0; gridLayout.marginLeft = 0; gridLayout.marginRight = 0; gridLayout.marginTop = 0; gridLayout.marginWidth = 0; gridLayout.verticalSpacing = 0; parent.setLayout( gridLayout ); // Search Field searchFieldComposite = new Composite( parent, SWT.NONE ); gridLayout = new GridLayout(); gridLayout.horizontalSpacing = 0; gridLayout.marginBottom = 0; gridLayout.marginHeight = 0; gridLayout.marginLeft = 0; gridLayout.marginRight = 0; gridLayout.marginTop = 0; gridLayout.marginWidth = 0; gridLayout.verticalSpacing = 0; searchFieldComposite.setLayout( gridLayout ); searchFieldComposite.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // This searchFieldCompositeSeparator is used to display correctly the searchFieldComposite, // since an empty composite does not display well. Label searchFieldCompositeSeparator = new Label( searchFieldComposite, SWT.SEPARATOR | SWT.HORIZONTAL ); GridData gridData = new GridData( SWT.FILL, SWT.NONE, true, false ); gridData.heightHint = 1; searchFieldCompositeSeparator.setLayoutData( gridData ); searchFieldCompositeSeparator.setVisible( false ); // Search Results Label searchResultsLabel = new Label( parent, SWT.NONE ); searchResultsLabel.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Separator Label Label separatorLabel2 = new Label( parent, SWT.SEPARATOR | SWT.HORIZONTAL ); separatorLabel2.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Create the table createTableViewer(); setSearchResultsLabel( null, 0 ); new SearchViewController( this ); } /** * Create the Search Field Sections. */ private void createSearchField() { // Search Inner Composite searchFieldInnerComposite = new Composite( searchFieldComposite, SWT.NONE ); GridLayout searchFieldInnerCompositeGridLayout = new GridLayout( 4, false ); searchFieldInnerCompositeGridLayout.horizontalSpacing = 1; searchFieldInnerCompositeGridLayout.verticalSpacing = 1; searchFieldInnerCompositeGridLayout.marginHeight = 1; searchFieldInnerCompositeGridLayout.marginWidth = 2; searchFieldInnerComposite.setLayout( searchFieldInnerCompositeGridLayout ); searchFieldInnerComposite.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Search Label Label searchFieldLabel = new Label( searchFieldInnerComposite, SWT.NONE ); searchFieldLabel.setText( "Search:" ); searchFieldLabel.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, false, false ) ); // Search Text Field searchField = new Text( searchFieldInnerComposite, SWT.BORDER ); if ( searchString != null ) { searchField.setText( searchString ); } searchField.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); searchField.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { validateSearchField(); } } ); searchField.addKeyListener( new KeyAdapter() { public void keyReleased( KeyEvent e ) { if ( e.keyCode == SWT.ARROW_DOWN ) { resultsTable.setFocus(); } else if ( ( e.keyCode == Action.findKeyCode( "RETURN" ) ) || ( e.keyCode == 16777296 /* The "Enter" Key at the bottom right of the keyboard */) ) //$NON-NLS-1$ { search(); } } } ); // Search Toolbar final ToolBar searchToolBar = new ToolBar( searchFieldInnerComposite, SWT.HORIZONTAL | SWT.FLAT ); // Creating the Search In ToolItem final ToolItem searchInToolItem = new ToolItem( searchToolBar, SWT.DROP_DOWN ); searchInToolItem.setText( "Search In" ); // Adding the action to display the Menu when the item is clicked searchInToolItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { Rectangle rect = searchInToolItem.getBounds(); Point pt = new Point( rect.x, rect.y + rect.height ); pt = searchToolBar.toDisplay( pt ); Menu menu = createSearchInMenu(); menu.setLocation( pt.x, pt.y ); menu.setVisible( true ); } } ); new ToolItem( searchToolBar, SWT.SEPARATOR ); final ToolItem scopeToolItem = new ToolItem( searchToolBar, SWT.DROP_DOWN ); scopeToolItem.setText( "Scope" ); // Adding the action to display the Menu when the item is clicked scopeToolItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { Rectangle rect = scopeToolItem.getBounds(); Point pt = new Point( rect.x, rect.y + rect.height ); pt = searchToolBar.toDisplay( pt ); Menu menu = createScopeMenu(); menu.setLocation( pt.x, pt.y ); menu.setVisible( true ); } } ); searchToolBar.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, false, false ) ); // Search Button searchButton = new Button( searchFieldInnerComposite, SWT.PUSH | SWT.DOWN ); searchButton.setEnabled( false ); searchButton.setImage( AbstractUIPlugin.imageDescriptorFromPlugin( Activator.PLUGIN_ID, PluginConstants.IMG_SEARCH ).createImage() ); searchButton.setToolTipText( "Search" ); searchButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { search(); } } ); searchButton.setLayoutData( new GridData( SWT.NONE, SWT.CENTER, false, false ) ); // Separator Label separatorLabel = new Label( searchFieldComposite, SWT.SEPARATOR | SWT.HORIZONTAL ); separatorLabel.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Search In Menu * * @return * the Search In menu */ public Menu createSearchInMenu() { final IDialogSettings settings = Activator.getDefault().getDialogSettings(); // Creating the associated Menu Menu searchInMenu = new Menu( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.POP_UP ); // Filling the menu // Aliases final MenuItem aliasesMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); aliasesMenuItem.setText( "Aliases" ); aliasesMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_ALIASES, aliasesMenuItem.getSelection() ); } } ); // OID final MenuItem oidMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); oidMenuItem.setText( "OID" ); oidMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_OID, oidMenuItem.getSelection() ); } } ); // Description final MenuItem descriptionMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); descriptionMenuItem.setText( "Description" ); descriptionMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_DESCRIPTION, descriptionMenuItem .getSelection() ); } } ); // Separator new MenuItem( searchInMenu, SWT.SEPARATOR ); // Superior final MenuItem superiorMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); superiorMenuItem.setText( "Superior" ); superiorMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_SUPERIOR, superiorMenuItem.getSelection() ); } } ); // Syntax final MenuItem syntaxMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); syntaxMenuItem.setText( "Syntax" ); syntaxMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_SYNTAX, syntaxMenuItem.getSelection() ); } } ); // Matching Rules final MenuItem matchingRulesMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); matchingRulesMenuItem.setText( "Matching Rules" ); matchingRulesMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_MATCHING_RULES, matchingRulesMenuItem .getSelection() ); } } ); // Separator new MenuItem( searchInMenu, SWT.SEPARATOR ); // Superiors final MenuItem superiorsMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); superiorsMenuItem.setText( "Superiors" ); superiorsMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_SUPERIORS, superiorsMenuItem.getSelection() ); } } ); // Mandatory Attributes final MenuItem mandatoryAttributesMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); mandatoryAttributesMenuItem.setText( "Mandatory Attributes" ); mandatoryAttributesMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_MANDATORY_ATTRIBUTES, mandatoryAttributesMenuItem.getSelection() ); } } ); // Optional Attributes final MenuItem optionalAttributesMenuItem = new MenuItem( searchInMenu, SWT.CHECK ); optionalAttributesMenuItem.setText( "Optional Attributes" ); optionalAttributesMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_OPTIONAL_ATTRIBUTES, optionalAttributesMenuItem.getSelection() ); } } ); if ( settings.get( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_ALIASES ) == null ) { aliasesMenuItem.setSelection( true ); } else { aliasesMenuItem.setSelection( settings.getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_ALIASES ) ); } if ( settings.get( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_OID ) == null ) { oidMenuItem.setSelection( true ); } else { oidMenuItem.setSelection( settings.getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_OID ) ); } if ( settings.get( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_DESCRIPTION ) == null ) { descriptionMenuItem.setSelection( true ); } else { descriptionMenuItem.setSelection( settings .getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_DESCRIPTION ) ); } superiorMenuItem.setSelection( settings.getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_SUPERIOR ) ); syntaxMenuItem.setSelection( settings.getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_SYNTAX ) ); matchingRulesMenuItem.setSelection( settings .getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_MATCHING_RULES ) ); superiorsMenuItem.setSelection( settings.getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_SUPERIORS ) ); mandatoryAttributesMenuItem.setSelection( settings .getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_MANDATORY_ATTRIBUTES ) ); optionalAttributesMenuItem.setSelection( settings .getBoolean( PluginConstants.PREFS_SEARCH_PAGE_SEARCH_IN_OPTIONAL_ATTRIBUTES ) ); return searchInMenu; } /** * Creates the Scope Menu * * @return * the Scope menu */ public Menu createScopeMenu() { final IDialogSettings settings = Activator.getDefault().getDialogSettings(); // Creating the associated Menu Menu scopeMenu = new Menu( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.POP_UP ); // Filling the menu // Attribute Types And Object Classes final MenuItem attributeTypesAndObjectClassesMenuItem = new MenuItem( scopeMenu, SWT.RADIO ); attributeTypesAndObjectClassesMenuItem.setText( "Attribute Types And Object Classes" ); attributeTypesAndObjectClassesMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SCOPE, PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ); } } ); // Attributes Type Only final MenuItem attributesTypesOnlyMenuItem = new MenuItem( scopeMenu, SWT.RADIO ); attributesTypesOnlyMenuItem.setText( "Attribute Types Only" ); attributesTypesOnlyMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SCOPE, PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_ONLY ); } } ); // Object Classes Only final MenuItem objectClassesMenuItem = new MenuItem( scopeMenu, SWT.RADIO ); objectClassesMenuItem.setText( "Object Classes Only" ); objectClassesMenuItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { settings.put( PluginConstants.PREFS_SEARCH_PAGE_SCOPE, PluginConstants.PREFS_SEARCH_PAGE_SCOPE_OC_ONLY ); } } ); if ( settings.get( PluginConstants.PREFS_SEARCH_PAGE_SCOPE ) == null ) { attributeTypesAndObjectClassesMenuItem.setSelection( true ); } else { switch ( settings.getInt( PluginConstants.PREFS_SEARCH_PAGE_SCOPE ) ) { case PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC: attributeTypesAndObjectClassesMenuItem.setSelection( true ); break; case PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_ONLY: attributesTypesOnlyMenuItem.setSelection( true ); break; case PluginConstants.PREFS_SEARCH_PAGE_SCOPE_OC_ONLY: objectClassesMenuItem.setSelection( true ); break; } } return scopeMenu; } /** * Creates the TableViewer. */ private void createTableViewer() { // Creating the TableViewer resultsTable = new Table( parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION ); GridData gridData = new GridData( SWT.FILL, SWT.FILL, true, true ); resultsTable.setLayoutData( gridData ); resultsTable.setLinesVisible( true ); // Creating the TableViewer resultsTableViewer = new TableViewer( resultsTable ); resultsTableViewer.setLabelProvider( new DecoratingLabelProvider( new SearchViewLabelProvider(), Activator .getDefault().getWorkbench().getDecoratorManager().getLabelDecorator() ) ); resultsTableViewer.setContentProvider( new SearchViewContentProvider() ); // Adding listeners resultsTable.addKeyListener( new KeyAdapter() { public void keyPressed( KeyEvent e ) { if ( ( e.keyCode == Action.findKeyCode( "RETURN" ) ) || ( e.keyCode == 16777296 /* The "Enter" Key at the bottom right of the keyboard */) ) // return key { openEditor(); } } } ); resultsTableViewer.addDoubleClickListener( new IDoubleClickListener() { public void doubleClick( DoubleClickEvent event ) { openEditor(); } } ); } /** * Open the editor associated with the current selection in the table. */ private void openEditor() { if ( Activator.getDefault().getSchemaHandler() != null ) { StructuredSelection selection = ( StructuredSelection ) resultsTableViewer.getSelection(); if ( !selection.isEmpty() ) { Object item = selection.getFirstElement(); IEditorInput input = null; String editorId = null; // Here is the double clicked item if ( item instanceof AttributeTypeImpl ) { input = new AttributeTypeEditorInput( ( AttributeTypeImpl ) item ); editorId = AttributeTypeEditor.ID; } else if ( item instanceof ObjectClassImpl ) { input = new ObjectClassEditorInput( ( ObjectClassImpl ) item ); editorId = ObjectClassEditor.ID; } // Let's open the editor if ( input != null ) { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor( input, editorId ); } catch ( PartInitException exception ) { PluginUtils.logError( "An error occured when opening the editor.", exception ); ViewUtils.displayErrorMessageBox( "Error", "An error occured when opening the editor." ); } } } } } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ public void setFocus() { if ( searchField != null && !searchField.isDisposed() ) { searchField.setFocus(); } else { resultsTable.setFocus(); } } /** * Shows the Search Field Section. */ public void showSearchFieldSection() { createSearchField(); parent.layout( true, true ); searchField.setFocus(); validateSearchField(); } /** * Hides the Search Field Section. */ public void hideSearchFieldSection() { if ( searchFieldInnerComposite != null ) { searchFieldInnerComposite.dispose(); searchFieldInnerComposite = null; } if ( separatorLabel != null ) { separatorLabel.dispose(); separatorLabel = null; } parent.layout( true, true ); resultsTable.setFocus(); } private void validateSearchField() { searchButton.setEnabled( searchField.getText().length() > 0 ); } /** * Sets the Search Input. * * @param searchString * the search String * @param searchIn * the search In * @param scope * the scope */ public void setSearchInput( String searchString, SearchInEnum[] searchIn, int scope ) { this.searchString = searchString; // Saving search String and Search Scope to dialog settings SearchPage.addSearchStringHistory( searchString ); SearchPage.saveSearchScope( Arrays.asList( searchIn ) ); if ( ( searchField != null ) && ( !searchField.isDisposed() ) ) { searchField.setText( searchString ); validateSearchField(); } List<SchemaObject> results = search( searchString, searchIn, scope ); setSearchResultsLabel( searchString, results.size() ); resultsTableViewer.setInput( results ); } /** * Searches the objects corresponding to the search parameters. * * @param searchString * the search String * @param searchIn * the search In * @param scope * the scope */ private List<SchemaObject> search( String searchString, SearchInEnum[] searchIn, int scope ) { List<SchemaObject> searchResults = new ArrayList<SchemaObject>(); if ( searchString != null ) { - String computedSearchString = searchString.replaceAll( "\\*", "\\\\w*" ); + String computedSearchString = searchString.replaceAll( "\\*", "\\\\S*" ); computedSearchString = computedSearchString.replaceAll( "\\?", ".*" ); Pattern pattern = Pattern.compile( computedSearchString, Pattern.CASE_INSENSITIVE ); SchemaHandler schemaHandler = Activator.getDefault().getSchemaHandler(); if ( schemaHandler != null ) { List<SearchInEnum> searchScope = new ArrayList<SearchInEnum>( Arrays.asList( searchIn ) ); if ( ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ) || ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_ONLY ) ) { // Looping on attribute types List<AttributeTypeImpl> attributeTypes = schemaHandler.getAttributeTypes(); for ( AttributeTypeImpl at : attributeTypes ) { // Aliases if ( searchScope.contains( SearchInEnum.ALIASES ) ) { if ( checkArray( pattern, at.getNames() ) ) { searchResults.add( at ); continue; } } // OID if ( searchScope.contains( SearchInEnum.OID ) ) { if ( checkString( pattern, at.getOid() ) ) { searchResults.add( at ); continue; } } // Description if ( searchScope.contains( SearchInEnum.DESCRIPTION ) ) { if ( checkString( pattern, at.getDescription() ) ) { searchResults.add( at ); continue; } } // Superior if ( searchScope.contains( SearchInEnum.SUPERIOR ) ) { if ( checkString( pattern, at.getSuperiorName() ) ) { searchResults.add( at ); continue; } } // Syntax if ( searchScope.contains( SearchInEnum.SYNTAX ) ) { if ( checkString( pattern, at.getSyntaxOid() ) ) { searchResults.add( at ); continue; } } // Matching Rules if ( searchScope.contains( SearchInEnum.MATCHING_RULES ) ) { // Equality if ( checkString( pattern, at.getEqualityName() ) ) { searchResults.add( at ); continue; } // Ordering if ( checkString( pattern, at.getOrderingName() ) ) { searchResults.add( at ); continue; } // Substring if ( checkString( pattern, at.getSubstrName() ) ) { searchResults.add( at ); continue; } } } } if ( ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ) || ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_OC_ONLY ) ) { // Looping on object classes List<ObjectClassImpl> objectClasses = schemaHandler.getObjectClasses(); for ( ObjectClassImpl oc : objectClasses ) { // Aliases if ( searchScope.contains( SearchInEnum.ALIASES ) ) { if ( checkArray( pattern, oc.getNames() ) ) { searchResults.add( oc ); continue; } } // OID if ( searchScope.contains( SearchInEnum.OID ) ) { if ( checkString( pattern, oc.getOid() ) ) { searchResults.add( oc ); continue; } } // Description if ( searchScope.contains( SearchInEnum.DESCRIPTION ) ) { if ( checkString( pattern, oc.getDescription() ) ) { searchResults.add( oc ); continue; } } // Superiors if ( searchScope.contains( SearchInEnum.SUPERIORS ) ) { if ( checkArray( pattern, oc.getSuperClassesNames() ) ) { searchResults.add( oc ); continue; } } // Mandatory Attributes if ( searchScope.contains( SearchInEnum.MANDATORY_ATTRIBUTES ) ) { if ( checkArray( pattern, oc.getMustNamesList() ) ) { searchResults.add( oc ); continue; } } // Optional Attributes if ( searchScope.contains( SearchInEnum.OPTIONAL_ATTRIBUTES ) ) { if ( checkArray( pattern, oc.getMayNamesList() ) ) { searchResults.add( oc ); continue; } } } } } } return searchResults; } /** * Check an array with the given pattern. * * @param pattern * the Regex pattern * @param array * the array * @return * true if the pattern matches one of the aliases, false, if not. */ private boolean checkArray( Pattern pattern, String[] array ) { if ( array != null ) { for ( String string : array ) { return pattern.matcher( string ).matches(); } } return false; } private boolean checkString( Pattern pattern, String string ) { if ( string != null ) { return pattern.matcher( string ).matches(); } return false; } /** * Launches the search from the search fields views. */ private void search() { String searchString = searchField.getText(); List<SearchInEnum> searchScope = SearchPage.loadSearchIn(); setSearchInput( searchString, searchScope.toArray( new SearchInEnum[0] ), SearchPage.loadScope() ); } /** * Refresh the overview label with the number of results. * * @param searchString * the search String * @param resultsCount * the number of results */ public void setSearchResultsLabel( String searchString, int resultsCount ) { StringBuffer sb = new StringBuffer(); if ( searchString == null ) { sb.append( "No search" ); } else { // Search String sb.append( "'" + searchString + "'" ); sb.append( " - " ); // Search results count sb.append( resultsCount ); sb.append( " " ); if ( resultsCount > 1 ) { sb.append( "matches" ); } else { sb.append( "match" ); } sb.append( " in workspace" ); } searchResultsLabel.setText( sb.toString() ); } /** * Runs the current search again. */ public void runCurrentSearchAgain() { if ( searchString != null ) { setSearchInput( searchString, SearchPage.loadSearchIn().toArray( new SearchInEnum[0] ), SearchPage .loadScope() ); } } /** * Gets the Search String. * * @return * the Search String or null if no Search String is set. */ public String getSearchString() { return searchString; } /** * Refreshes the view. */ public void refresh() { resultsTableViewer.refresh(); } }
true
true
private List<SchemaObject> search( String searchString, SearchInEnum[] searchIn, int scope ) { List<SchemaObject> searchResults = new ArrayList<SchemaObject>(); if ( searchString != null ) { String computedSearchString = searchString.replaceAll( "\\*", "\\\\w*" ); computedSearchString = computedSearchString.replaceAll( "\\?", ".*" ); Pattern pattern = Pattern.compile( computedSearchString, Pattern.CASE_INSENSITIVE ); SchemaHandler schemaHandler = Activator.getDefault().getSchemaHandler(); if ( schemaHandler != null ) { List<SearchInEnum> searchScope = new ArrayList<SearchInEnum>( Arrays.asList( searchIn ) ); if ( ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ) || ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_ONLY ) ) { // Looping on attribute types List<AttributeTypeImpl> attributeTypes = schemaHandler.getAttributeTypes(); for ( AttributeTypeImpl at : attributeTypes ) { // Aliases if ( searchScope.contains( SearchInEnum.ALIASES ) ) { if ( checkArray( pattern, at.getNames() ) ) { searchResults.add( at ); continue; } } // OID if ( searchScope.contains( SearchInEnum.OID ) ) { if ( checkString( pattern, at.getOid() ) ) { searchResults.add( at ); continue; } } // Description if ( searchScope.contains( SearchInEnum.DESCRIPTION ) ) { if ( checkString( pattern, at.getDescription() ) ) { searchResults.add( at ); continue; } } // Superior if ( searchScope.contains( SearchInEnum.SUPERIOR ) ) { if ( checkString( pattern, at.getSuperiorName() ) ) { searchResults.add( at ); continue; } } // Syntax if ( searchScope.contains( SearchInEnum.SYNTAX ) ) { if ( checkString( pattern, at.getSyntaxOid() ) ) { searchResults.add( at ); continue; } } // Matching Rules if ( searchScope.contains( SearchInEnum.MATCHING_RULES ) ) { // Equality if ( checkString( pattern, at.getEqualityName() ) ) { searchResults.add( at ); continue; } // Ordering if ( checkString( pattern, at.getOrderingName() ) ) { searchResults.add( at ); continue; } // Substring if ( checkString( pattern, at.getSubstrName() ) ) { searchResults.add( at ); continue; } } } } if ( ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ) || ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_OC_ONLY ) ) { // Looping on object classes List<ObjectClassImpl> objectClasses = schemaHandler.getObjectClasses(); for ( ObjectClassImpl oc : objectClasses ) { // Aliases if ( searchScope.contains( SearchInEnum.ALIASES ) ) { if ( checkArray( pattern, oc.getNames() ) ) { searchResults.add( oc ); continue; } } // OID if ( searchScope.contains( SearchInEnum.OID ) ) { if ( checkString( pattern, oc.getOid() ) ) { searchResults.add( oc ); continue; } } // Description if ( searchScope.contains( SearchInEnum.DESCRIPTION ) ) { if ( checkString( pattern, oc.getDescription() ) ) { searchResults.add( oc ); continue; } } // Superiors if ( searchScope.contains( SearchInEnum.SUPERIORS ) ) { if ( checkArray( pattern, oc.getSuperClassesNames() ) ) { searchResults.add( oc ); continue; } } // Mandatory Attributes if ( searchScope.contains( SearchInEnum.MANDATORY_ATTRIBUTES ) ) { if ( checkArray( pattern, oc.getMustNamesList() ) ) { searchResults.add( oc ); continue; } } // Optional Attributes if ( searchScope.contains( SearchInEnum.OPTIONAL_ATTRIBUTES ) ) { if ( checkArray( pattern, oc.getMayNamesList() ) ) { searchResults.add( oc ); continue; } } } } } } return searchResults; }
private List<SchemaObject> search( String searchString, SearchInEnum[] searchIn, int scope ) { List<SchemaObject> searchResults = new ArrayList<SchemaObject>(); if ( searchString != null ) { String computedSearchString = searchString.replaceAll( "\\*", "\\\\S*" ); computedSearchString = computedSearchString.replaceAll( "\\?", ".*" ); Pattern pattern = Pattern.compile( computedSearchString, Pattern.CASE_INSENSITIVE ); SchemaHandler schemaHandler = Activator.getDefault().getSchemaHandler(); if ( schemaHandler != null ) { List<SearchInEnum> searchScope = new ArrayList<SearchInEnum>( Arrays.asList( searchIn ) ); if ( ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ) || ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_ONLY ) ) { // Looping on attribute types List<AttributeTypeImpl> attributeTypes = schemaHandler.getAttributeTypes(); for ( AttributeTypeImpl at : attributeTypes ) { // Aliases if ( searchScope.contains( SearchInEnum.ALIASES ) ) { if ( checkArray( pattern, at.getNames() ) ) { searchResults.add( at ); continue; } } // OID if ( searchScope.contains( SearchInEnum.OID ) ) { if ( checkString( pattern, at.getOid() ) ) { searchResults.add( at ); continue; } } // Description if ( searchScope.contains( SearchInEnum.DESCRIPTION ) ) { if ( checkString( pattern, at.getDescription() ) ) { searchResults.add( at ); continue; } } // Superior if ( searchScope.contains( SearchInEnum.SUPERIOR ) ) { if ( checkString( pattern, at.getSuperiorName() ) ) { searchResults.add( at ); continue; } } // Syntax if ( searchScope.contains( SearchInEnum.SYNTAX ) ) { if ( checkString( pattern, at.getSyntaxOid() ) ) { searchResults.add( at ); continue; } } // Matching Rules if ( searchScope.contains( SearchInEnum.MATCHING_RULES ) ) { // Equality if ( checkString( pattern, at.getEqualityName() ) ) { searchResults.add( at ); continue; } // Ordering if ( checkString( pattern, at.getOrderingName() ) ) { searchResults.add( at ); continue; } // Substring if ( checkString( pattern, at.getSubstrName() ) ) { searchResults.add( at ); continue; } } } } if ( ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_AT_AND_OC ) || ( scope == PluginConstants.PREFS_SEARCH_PAGE_SCOPE_OC_ONLY ) ) { // Looping on object classes List<ObjectClassImpl> objectClasses = schemaHandler.getObjectClasses(); for ( ObjectClassImpl oc : objectClasses ) { // Aliases if ( searchScope.contains( SearchInEnum.ALIASES ) ) { if ( checkArray( pattern, oc.getNames() ) ) { searchResults.add( oc ); continue; } } // OID if ( searchScope.contains( SearchInEnum.OID ) ) { if ( checkString( pattern, oc.getOid() ) ) { searchResults.add( oc ); continue; } } // Description if ( searchScope.contains( SearchInEnum.DESCRIPTION ) ) { if ( checkString( pattern, oc.getDescription() ) ) { searchResults.add( oc ); continue; } } // Superiors if ( searchScope.contains( SearchInEnum.SUPERIORS ) ) { if ( checkArray( pattern, oc.getSuperClassesNames() ) ) { searchResults.add( oc ); continue; } } // Mandatory Attributes if ( searchScope.contains( SearchInEnum.MANDATORY_ATTRIBUTES ) ) { if ( checkArray( pattern, oc.getMustNamesList() ) ) { searchResults.add( oc ); continue; } } // Optional Attributes if ( searchScope.contains( SearchInEnum.OPTIONAL_ATTRIBUTES ) ) { if ( checkArray( pattern, oc.getMayNamesList() ) ) { searchResults.add( oc ); continue; } } } } } } return searchResults; }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java index 2f733fa9c..ae5583d70 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java @@ -1,1039 +1,1049 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.build; import com.android.ide.eclipse.adt.AdtConstants; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.AndroidConstants; import com.android.ide.eclipse.adt.internal.project.AndroidManifestParser; import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper; import com.android.ide.eclipse.adt.internal.project.FixLaunchConfig; import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.BasicXmlErrorListener; import com.android.ide.eclipse.adt.internal.sdk.Sdk; import com.android.sdklib.AndroidVersion; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.SdkConstants; import com.android.sdklib.xml.ManifestConstants; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Pre Java Compiler. * This incremental builder performs 2 tasks: * <ul> * <li>compiles the resources located in the res/ folder, along with the * AndroidManifest.xml file into the R.java class.</li> * <li>compiles any .aidl files into a corresponding java file.</li> * </ul> * */ public class PreCompilerBuilder extends BaseBuilder { public static final String ID = "com.android.ide.eclipse.adt.PreCompilerBuilder"; //$NON-NLS-1$ private static final String PROPERTY_PACKAGE = "manifestPackage"; //$NON-NLS-1$ private static final String PROPERTY_COMPILE_RESOURCES = "compileResources"; //$NON-NLS-1$ private static final String PROPERTY_COMPILE_AIDL = "compileAidl"; //$NON-NLS-1$ /** * Single line aidl error<br> * "&lt;path&gt;:&lt;line&gt;: &lt;error&gt;" * or * "&lt;path&gt;:&lt;line&gt; &lt;error&gt;" */ private static Pattern sAidlPattern1 = Pattern.compile("^(.+?):(\\d+):?\\s(.+)$"); //$NON-NLS-1$ /** * Data to temporarly store aidl source file information */ static class AidlData { IFile aidlFile; IFolder sourceFolder; AidlData(IFolder sourceFolder, IFile aidlFile) { this.sourceFolder = sourceFolder; this.aidlFile = aidlFile; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof AidlData) { AidlData file = (AidlData)obj; return aidlFile.equals(file.aidlFile) && sourceFolder.equals(file.sourceFolder); } return false; } } /** * Resource Compile flag. This flag is reset to false after each successful compilation, and * stored in the project persistent properties. This allows the builder to remember its state * when the project is closed/opened. */ private boolean mMustCompileResources = false; /** List of .aidl files found that are modified or new. */ private final ArrayList<AidlData> mAidlToCompile = new ArrayList<AidlData>(); /** List of .aidl files that have been removed. */ private final ArrayList<AidlData> mAidlToRemove = new ArrayList<AidlData>(); /** cache of the java package defined in the manifest */ private String mManifestPackage; /** Output folder for generated Java File. Created on the Builder init * @see #startupOnInitialize() */ private IFolder mGenFolder; /** * Progress monitor used at the end of every build to refresh the content of the 'gen' folder * and set the generated files as derived. */ private DerivedProgressMonitor mDerivedProgressMonitor; /** * Progress monitor waiting the end of the process to set a persistent value * in a file. This is typically used in conjunction with <code>IResource.refresh()</code>, * since this call is asysnchronous, and we need to wait for it to finish for the file * to be known by eclipse, before we can call <code>resource.setPersistentProperty</code> on * a new file. */ private static class DerivedProgressMonitor implements IProgressMonitor { private boolean mCancelled = false; private final ArrayList<IFile> mFileList = new ArrayList<IFile>(); private boolean mDone = false; public DerivedProgressMonitor() { } void addFile(IFile file) { mFileList.add(file); } void reset() { mFileList.clear(); mDone = false; } public void beginTask(String name, int totalWork) { } public void done() { if (mDone == false) { mDone = true; for (IFile file : mFileList) { if (file.exists()) { try { file.setDerived(true); } catch (CoreException e) { // This really shouldn't happen since we check that the resource exist. // Worst case scenario, the resource isn't marked as derived. } } } } } public void internalWorked(double work) { } public boolean isCanceled() { return mCancelled; } public void setCanceled(boolean value) { mCancelled = value; } public void setTaskName(String name) { } public void subTask(String name) { } public void worked(int work) { } } public PreCompilerBuilder() { super(); } // build() returns a list of project from which this project depends for future compilation. @SuppressWarnings("unchecked") @Override protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { try { mDerivedProgressMonitor.reset(); // First thing we do is go through the resource delta to not // lose it if we have to abort the build for any reason. // get the project objects IProject project = getProject(); // Top level check to make sure the build can move forward. abortOnBadSetup(project); IJavaProject javaProject = JavaCore.create(project); IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project); // now we need to get the classpath list ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); PreCompilerDeltaVisitor dv = null; String javaPackage = null; String minSdkVersion = null; if (kind == FULL_BUILD) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Pre_Compiler); mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Pre_Compiler); // Go through the resources and see if something changed. // Even if the mCompileResources flag is true from a previously aborted // build, we need to go through the Resource delta to get a possible // list of aidl files to compile/remove. IResourceDelta delta = getDelta(project); if (delta == null) { mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList); delta.accept(dv); // record the state mMustCompileResources |= dv.getCompileResources(); if (dv.getForceAidlCompile()) { buildAidlCompilationList(project, sourceFolderPathList); } else { // handle aidl modification, and update mMustCompileAidl mergeAidlFileModifications(dv.getAidlToCompile(), dv.getAidlToRemove()); } // get the java package from the visitor javaPackage = dv.getManifestPackage(); minSdkVersion = dv.getMinSdkVersion(); } } // store the build status in the persistent storage saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources); // if there was some XML errors, we just return w/o doing // anything since we've put some markers in the files anyway. if (dv != null && dv.mXmlError) { AdtPlugin.printErrorToConsole(project, Messages.Xml_Error); // This interrupts the build. The next builders will not run. stopBuild(Messages.Xml_Error); } // get the manifest file IFile manifest = AndroidManifestParser.getManifest(project); if (manifest == null) { String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses manifest (which is now guaranteed // to be null) will actually be executed or not. } // lets check the XML of the manifest first, if that hasn't been done by the // resource delta visitor yet. if (dv == null || dv.getCheckedManifestXml() == false) { BasicXmlErrorListener errorListener = new BasicXmlErrorListener(); AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest, errorListener); if (errorListener.mHasXmlError == true) { // there was an error in the manifest, its file has been marked, // by the XmlErrorHandler. // We return; String msg = String.format(Messages.s_Contains_Xml_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); // This interrupts the build. The next builders will not run. stopBuild(msg); } // get the java package from the parser javaPackage = parser.getPackage(); minSdkVersion = parser.getApiLevelRequirement(); } if (minSdkVersion != null) { int minSdkValue = -1; try { minSdkValue = Integer.parseInt(minSdkVersion); } catch (NumberFormatException e) { // it's ok, it means minSdkVersion contains a (hopefully) valid codename. } AndroidVersion projectVersion = projectTarget.getVersion(); if (minSdkValue != -1) { String codename = projectVersion.getCodename(); if (codename != null) { // integer minSdk when the target is a preview => fatal error String msg = String.format( - "Platform %1$s is a preview and requires appication manifests to set %2$s to '%3$s'", - codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, - codename); + "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", + codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (minSdkValue < projectVersion.getApiLevel()) { // integer minSdk is not high enough for the target => warning String msg = String.format( "Manifest min SDK version (%1$s) is lower than project target API level (%2$d)", minSdkVersion, projectVersion.getApiLevel()); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_WARNING); } } else { // looks like the min sdk is a codename, check it matches the codename // of the platform String codename = projectVersion.getCodename(); if (codename == null) { // platform is not a preview => fatal error String msg = String.format( "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (codename.equals(minSdkVersion) == false) { // platform and manifest codenames don't match => fatal error. String msg = String.format( "Value of manifest attribute '%1$s' does not match platform codename '%2$s'", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } } + } else if (projectTarget.getVersion().isPreview()) { + // else the minSdkVersion is not set but we are using a preview target. + // Display an error + String codename = projectTarget.getVersion().getCodename(); + String msg = String.format( + "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", + codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); + AdtPlugin.printErrorToConsole(project, msg); + BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, + IMarker.SEVERITY_ERROR); + stopBuild(msg); } if (javaPackage == null || javaPackage.length() == 0) { // looks like the AndroidManifest file isn't valid. String msg = String.format(Messages.s_Doesnt_Declare_Package_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses javaPackage (which is now guaranteed // to be null) will actually be executed or not. } // at this point we have the java package. We need to make sure it's not a different // package than the previous one that were built. if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) { // The manifest package has changed, the user may want to update // the launch configuration if (mManifestPackage != null) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Checking_Package_Change); FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage, javaPackage); flc.start(); } // now we delete the generated classes from their previous location deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS, mManifestPackage); deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS, mManifestPackage); // record the new manifest package, and save it. mManifestPackage = javaPackage; saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage); } if (mMustCompileResources) { // we need to figure out where to store the R class. // get the parent folder for R.java and update mManifestPackageSourceFolder IFolder packageFolder = getGenManifestPackageFolder(project); // get the resource folder IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES); // get the file system path IPath outputLocation = mGenFolder.getLocation(); IPath resLocation = resFolder.getLocation(); IPath manifestLocation = manifest == null ? null : manifest.getLocation(); // those locations have to exist for us to do something! if (outputLocation != null && resLocation != null && manifestLocation != null) { String osOutputPath = outputLocation.toOSString(); String osResPath = resLocation.toOSString(); String osManifestPath = manifestLocation.toOSString(); // remove the aapt markers removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE); removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Preparing_Generated_Files); // since the R.java file may be already existing in read-only // mode we need to make it readable so that aapt can overwrite // it IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS); // do the same for the Manifest.java class IFile manifestJavaFile = packageFolder.getFile( AndroidConstants.FN_MANIFEST_CLASS); // we actually need to delete the manifest.java as it may become empty and // in this case aapt doesn't generate an empty one, but instead doesn't // touch it. manifestJavaFile.delete(true, null); // launch aapt: create the command line ArrayList<String> array = new ArrayList<String>(); array.add(projectTarget.getPath(IAndroidTarget.AAPT)); array.add("package"); //$NON-NLS-1$ array.add("-m"); //$NON-NLS-1$ if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { array.add("-v"); //$NON-NLS-1$ } array.add("-J"); //$NON-NLS-1$ array.add(osOutputPath); array.add("-M"); //$NON-NLS-1$ array.add(osManifestPath); array.add("-S"); //$NON-NLS-1$ array.add(osResPath); array.add("-I"); //$NON-NLS-1$ array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR)); if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { StringBuilder sb = new StringBuilder(); for (String c : array) { sb.append(c); sb.append(' '); } String cmd_line = sb.toString(); AdtPlugin.printToConsole(project, cmd_line); } // launch int execError = 1; try { // launch the command line process Process process = Runtime.getRuntime().exec( array.toArray(new String[array.size()])); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process execError = grabProcessOutput(process, results); // attempt to parse the error output boolean parsingError = parseAaptOutput(results, project); // if we couldn't parse the output we display it in the console. if (parsingError) { if (execError != 0) { AdtPlugin.printErrorToConsole(project, results.toArray()); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL, project, results.toArray()); } } if (execError != 0) { // if the exec failed, and we couldn't parse the error output // (and therefore not all files that should have been marked, // were marked), we put a generic marker on the project and abort. if (parsingError) { markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR); } AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.AAPT_Error); // abort if exec failed. // This interrupts the build. The next builders will not run. stopBuild(Messages.AAPT_Error); } } catch (IOException e1) { // something happen while executing the process, // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } catch (InterruptedException e) { // we got interrupted waiting for the process to end... // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } // if the return code was OK, we refresh the folder that // contains R.java to force a java recompile. if (execError == 0) { // now add the R.java/Manifest.java to the list of file to be marked // as derived. mDerivedProgressMonitor.addFile(rJavaFile); mDerivedProgressMonitor.addFile(manifestJavaFile); // build has been done. reset the state of the builder mMustCompileResources = false; // and store it saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources); } } } else { // nothing to do } // now handle the aidl stuff. boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor); if (aidlStatus == false && mMustCompileResources == false) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Nothing_To_Compile); } } finally { // refresh the 'gen' source folder. Once this is done with the custom progress // monitor to mark all new files as derived mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor); } return null; } @Override protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(), Messages.Removing_Generated_Classes); // remove all the derived resources from the 'gen' source folder. removeDerivedResources(mGenFolder, monitor); } @Override protected void startupOnInitialize() { super.startupOnInitialize(); mDerivedProgressMonitor = new DerivedProgressMonitor(); IProject project = getProject(); // load the previous IFolder and java package. mManifestPackage = loadProjectStringProperty(PROPERTY_PACKAGE); // get the source folder in which all the Java files are created mGenFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES); // Load the current compile flags. We ask for true if not found to force a // recompile. mMustCompileResources = loadProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, true); boolean mustCompileAidl = loadProjectBooleanProperty(PROPERTY_COMPILE_AIDL, true); // if we stored that we have to compile some aidl, we build the list that will compile them // all if (mustCompileAidl) { IJavaProject javaProject = JavaCore.create(project); ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); buildAidlCompilationList(project, sourceFolderPathList); } } /** * Delete the a generated java class associated with the specified java package. * @param filename Name of the generated file to remove. * @param javaPackage the old java package */ private void deleteObsoleteGeneratedClass(String filename, String javaPackage) { if (javaPackage == null) { return; } IPath packagePath = getJavaPackagePath(javaPackage); IPath iPath = packagePath.append(filename); // Find a matching resource object. IResource javaFile = mGenFolder.findMember(iPath); if (javaFile != null && javaFile.exists() && javaFile.getType() == IResource.FILE) { try { // delete javaFile.delete(true, null); // refresh parent javaFile.getParent().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } catch (CoreException e) { // failed to delete it, the user will have to delete it manually. String message = String.format(Messages.Delete_Obsolete_Error, javaFile.getFullPath()); IProject project = getProject(); AdtPlugin.printErrorToConsole(project, message); AdtPlugin.printErrorToConsole(project, e.getMessage()); } } } /** * Creates a relative {@link IPath} from a java package. * @param javaPackageName the java package. */ private IPath getJavaPackagePath(String javaPackageName) { // convert the java package into path String[] segments = javaPackageName.split(AndroidConstants.RE_DOT); StringBuilder path = new StringBuilder(); for (String s : segments) { path.append(AndroidConstants.WS_SEP_CHAR); path.append(s); } return new Path(path.toString()); } /** * Returns an {@link IFolder} (located inside the 'gen' source folder), that matches the * package defined in the manifest. This {@link IFolder} may not actually exist * (aapt will create it anyway). * @param project The project. * @return the {@link IFolder} that will contain the R class or null if the folder was not found. * @throws CoreException */ private IFolder getGenManifestPackageFolder(IProject project) throws CoreException { // get the path for the package IPath packagePath = getJavaPackagePath(mManifestPackage); // get a folder for this path under the 'gen' source folder, and return it. // This IFolder may not reference an actual existing folder. return mGenFolder.getFolder(packagePath); } /** * Compiles aidl files into java. This will also removes old java files * created from aidl files that are now gone. * @param projectTarget Target of the project * @param sourceFolders the list of source folders, relative to the workspace. * @param monitor the projess monitor * @returns true if it did something * @throws CoreException */ private boolean handleAidl(IAndroidTarget projectTarget, ArrayList<IPath> sourceFolders, IProgressMonitor monitor) throws CoreException { if (mAidlToCompile.size() == 0 && mAidlToRemove.size() == 0) { return false; } // create the command line String[] command = new String[4 + sourceFolders.size()]; int index = 0; command[index++] = projectTarget.getPath(IAndroidTarget.AIDL); command[index++] = "-p" + Sdk.getCurrent().getTarget(getProject()).getPath( //$NON-NLS-1$ IAndroidTarget.ANDROID_AIDL); // since the path are relative to the workspace and not the project itself, we need // the workspace root. IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); for (IPath p : sourceFolders) { IFolder f = wsRoot.getFolder(p); command[index++] = "-I" + f.getLocation().toOSString(); //$NON-NLS-1$ } // list of files that have failed compilation. ArrayList<AidlData> stillNeedCompilation = new ArrayList<AidlData>(); // if an aidl file is being removed before we managed to compile it, it'll be in // both list. We *need* to remove it from the compile list or it'll never go away. for (AidlData aidlFile : mAidlToRemove) { int pos = mAidlToCompile.indexOf(aidlFile); if (pos != -1) { mAidlToCompile.remove(pos); } } // loop until we've compile them all for (AidlData aidlData : mAidlToCompile) { // Remove the AIDL error markers from the aidl file removeMarkersFromFile(aidlData.aidlFile, AndroidConstants.MARKER_AIDL); // get the path of the source file. IPath sourcePath = aidlData.aidlFile.getLocation(); String osSourcePath = sourcePath.toOSString(); IFile javaFile = getGenDestinationFile(aidlData, true /*createFolders*/, monitor); // finish to set the command line. command[index] = osSourcePath; command[index + 1] = javaFile.getLocation().toOSString(); // launch the process if (execAidl(command, aidlData.aidlFile) == false) { // aidl failed. File should be marked. We add the file to the list // of file that will need compilation again. stillNeedCompilation.add(aidlData); // and we move on to the next one. continue; } else { // make sure the file will be marked as derived once we refresh the 'gen' source // folder. mDerivedProgressMonitor.addFile(javaFile); } } // change the list to only contains the file that have failed compilation mAidlToCompile.clear(); mAidlToCompile.addAll(stillNeedCompilation); // Remove the java files created from aidl files that have been removed. for (AidlData aidlData : mAidlToRemove) { IFile javaFile = getGenDestinationFile(aidlData, false /*createFolders*/, monitor); if (javaFile.exists()) { // This confirms the java file was generated by the builder, // we can delete the aidlFile. javaFile.delete(true, null); // Refresh parent. javaFile.getParent().refreshLocal(IResource.DEPTH_ONE, monitor); } } mAidlToRemove.clear(); // store the build state. If there are any files that failed to compile, we will // force a full aidl compile on the next project open. (unless a full compilation succeed // before the project is closed/re-opened.) // TODO: Optimize by saving only the files that need compilation saveProjectBooleanProperty(PROPERTY_COMPILE_AIDL , mAidlToCompile.size() > 0); return true; } /** * Returns the {@link IFile} handle to the destination file for a given aild source file * ({@link AidlData}). * @param aidlData the data for the aidl source file. * @param createFolders whether or not the parent folder of the destination should be created * if it does not exist. * @param monitor the progress monitor * @return the handle to the destination file. * @throws CoreException */ private IFile getGenDestinationFile(AidlData aidlData, boolean createFolders, IProgressMonitor monitor) throws CoreException { // build the destination folder path. // Use the path of the source file, except for the path leading to its source folder, // and for the last segment which is the filename. int segmentToSourceFolderCount = aidlData.sourceFolder.getFullPath().segmentCount(); IPath packagePath = aidlData.aidlFile.getFullPath().removeFirstSegments( segmentToSourceFolderCount).removeLastSegments(1); Path destinationPath = new Path(packagePath.toString()); // get an IFolder for this path. It's relative to the 'gen' folder already IFolder destinationFolder = mGenFolder.getFolder(destinationPath); // create it if needed. if (destinationFolder.exists() == false && createFolders) { createFolder(destinationFolder, monitor); } // Build the Java file name from the aidl name. String javaName = aidlData.aidlFile.getName().replaceAll(AndroidConstants.RE_AIDL_EXT, AndroidConstants.DOT_JAVA); // get the resource for the java file. IFile javaFile = destinationFolder.getFile(javaName); return javaFile; } /** * Creates the destination folder. Because * {@link IFolder#create(boolean, boolean, IProgressMonitor)} only works if the parent folder * already exists, this goes and ensure that all the parent folders actually exist, or it * creates them as well. * @param destinationFolder The folder to create * @param monitor the {@link IProgressMonitor}, * @throws CoreException */ private void createFolder(IFolder destinationFolder, IProgressMonitor monitor) throws CoreException { // check the parent exist and create if necessary. IContainer parent = destinationFolder.getParent(); if (parent.getType() == IResource.FOLDER && parent.exists() == false) { createFolder((IFolder)parent, monitor); } // create the folder. destinationFolder.create(true /*force*/, true /*local*/, new SubProgressMonitor(monitor, 10)); } /** * Execute the aidl command line, parse the output, and mark the aidl file * with any reported errors. * @param command the String array containing the command line to execute. * @param file The IFile object representing the aidl file being * compiled. * @return false if the exec failed, and build needs to be aborted. */ private boolean execAidl(String[] command, IFile file) { // do the exec try { Process p = Runtime.getRuntime().exec(command); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process int result = grabProcessOutput(p, results); // attempt to parse the error output boolean error = parseAidlOutput(results, file); // If the process failed and we couldn't parse the output // we pring a message, mark the project and exit if (result != 0 && error == true) { // display the message in the console. AdtPlugin.printErrorToConsole(getProject(), results.toArray()); // mark the project and exit markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AIDL_Errors, IMarker.SEVERITY_ERROR); return false; } } catch (IOException e) { // mark the project and exit String msg = String.format(Messages.AIDL_Exec_Error, command[0]); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); return false; } catch (InterruptedException e) { // mark the project and exit String msg = String.format(Messages.AIDL_Exec_Error, command[0]); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); return false; } return true; } /** * Goes through the build paths and fills the list of aidl files to compile * ({@link #mAidlToCompile}). * @param project The project. * @param sourceFolderPathList The list of source folder paths. */ private void buildAidlCompilationList(IProject project, ArrayList<IPath> sourceFolderPathList) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (IPath sourceFolderPath : sourceFolderPathList) { IFolder sourceFolder = root.getFolder(sourceFolderPath); // we don't look in the 'gen' source folder as there will be no source in there. if (sourceFolder.exists() && sourceFolder.equals(mGenFolder) == false) { scanFolderForAidl(sourceFolder, sourceFolder); } } } /** * Scans a folder and fills the list of aidl files to compile. * @param sourceFolder the root source folder. * @param folder The folder to scan. */ private void scanFolderForAidl(IFolder sourceFolder, IFolder folder) { try { IResource[] members = folder.members(); for (IResource r : members) { // get the type of the resource switch (r.getType()) { case IResource.FILE: // if this a file, check that the file actually exist // and that it's an aidl file if (r.exists() && AndroidConstants.EXT_AIDL.equalsIgnoreCase(r.getFileExtension())) { mAidlToCompile.add(new AidlData(sourceFolder, (IFile)r)); } break; case IResource.FOLDER: // recursively go through children scanFolderForAidl(sourceFolder, (IFolder)r); break; default: // this would mean it's a project or the workspace root // which is unlikely to happen. we do nothing break; } } } catch (CoreException e) { // Couldn't get the members list for some reason. Just return. } } /** * Parse the output of aidl and mark the file with any errors. * @param lines The output to parse. * @param file The file to mark with error. * @return true if the parsing failed, false if success. */ private boolean parseAidlOutput(ArrayList<String> lines, IFile file) { // nothing to parse? just return false; if (lines.size() == 0) { return false; } Matcher m; for (int i = 0; i < lines.size(); i++) { String p = lines.get(i); m = sAidlPattern1.matcher(p); if (m.matches()) { // we can ignore group 1 which is the location since we already // have a IFile object representing the aidl file. String lineStr = m.group(2); String msg = m.group(3); // get the line number int line = 0; try { line = Integer.parseInt(lineStr); } catch (NumberFormatException e) { // looks like the string we extracted wasn't a valid // file number. Parsing failed and we return true return true; } // mark the file BaseProjectHelper.addMarker(file, AndroidConstants.MARKER_AIDL, msg, line, IMarker.SEVERITY_ERROR); // success, go to the next line continue; } // invalid line format, flag as error, and bail return true; } return false; } /** * Merge the current list of aidl file to compile/remove with the new one. * @param toCompile List of file to compile * @param toRemove List of file to remove */ private void mergeAidlFileModifications(ArrayList<AidlData> toCompile, ArrayList<AidlData> toRemove) { // loop through the new toRemove list, and add it to the old one, // plus remove any file that was still to compile and that are now // removed for (AidlData r : toRemove) { if (mAidlToRemove.indexOf(r) == -1) { mAidlToRemove.add(r); } int index = mAidlToCompile.indexOf(r); if (index != -1) { mAidlToCompile.remove(index); } } // now loop through the new files to compile and add it to the list. // Also look for them in the remove list, this would mean that they // were removed, then added back, and we shouldn't remove them, just // recompile them. for (AidlData r : toCompile) { if (mAidlToCompile.indexOf(r) == -1) { mAidlToCompile.add(r); } int index = mAidlToRemove.indexOf(r); if (index != -1) { mAidlToRemove.remove(index); } } } }
false
true
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { try { mDerivedProgressMonitor.reset(); // First thing we do is go through the resource delta to not // lose it if we have to abort the build for any reason. // get the project objects IProject project = getProject(); // Top level check to make sure the build can move forward. abortOnBadSetup(project); IJavaProject javaProject = JavaCore.create(project); IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project); // now we need to get the classpath list ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); PreCompilerDeltaVisitor dv = null; String javaPackage = null; String minSdkVersion = null; if (kind == FULL_BUILD) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Pre_Compiler); mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Pre_Compiler); // Go through the resources and see if something changed. // Even if the mCompileResources flag is true from a previously aborted // build, we need to go through the Resource delta to get a possible // list of aidl files to compile/remove. IResourceDelta delta = getDelta(project); if (delta == null) { mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList); delta.accept(dv); // record the state mMustCompileResources |= dv.getCompileResources(); if (dv.getForceAidlCompile()) { buildAidlCompilationList(project, sourceFolderPathList); } else { // handle aidl modification, and update mMustCompileAidl mergeAidlFileModifications(dv.getAidlToCompile(), dv.getAidlToRemove()); } // get the java package from the visitor javaPackage = dv.getManifestPackage(); minSdkVersion = dv.getMinSdkVersion(); } } // store the build status in the persistent storage saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources); // if there was some XML errors, we just return w/o doing // anything since we've put some markers in the files anyway. if (dv != null && dv.mXmlError) { AdtPlugin.printErrorToConsole(project, Messages.Xml_Error); // This interrupts the build. The next builders will not run. stopBuild(Messages.Xml_Error); } // get the manifest file IFile manifest = AndroidManifestParser.getManifest(project); if (manifest == null) { String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses manifest (which is now guaranteed // to be null) will actually be executed or not. } // lets check the XML of the manifest first, if that hasn't been done by the // resource delta visitor yet. if (dv == null || dv.getCheckedManifestXml() == false) { BasicXmlErrorListener errorListener = new BasicXmlErrorListener(); AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest, errorListener); if (errorListener.mHasXmlError == true) { // there was an error in the manifest, its file has been marked, // by the XmlErrorHandler. // We return; String msg = String.format(Messages.s_Contains_Xml_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); // This interrupts the build. The next builders will not run. stopBuild(msg); } // get the java package from the parser javaPackage = parser.getPackage(); minSdkVersion = parser.getApiLevelRequirement(); } if (minSdkVersion != null) { int minSdkValue = -1; try { minSdkValue = Integer.parseInt(minSdkVersion); } catch (NumberFormatException e) { // it's ok, it means minSdkVersion contains a (hopefully) valid codename. } AndroidVersion projectVersion = projectTarget.getVersion(); if (minSdkValue != -1) { String codename = projectVersion.getCodename(); if (codename != null) { // integer minSdk when the target is a preview => fatal error String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%3$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (minSdkValue < projectVersion.getApiLevel()) { // integer minSdk is not high enough for the target => warning String msg = String.format( "Manifest min SDK version (%1$s) is lower than project target API level (%2$d)", minSdkVersion, projectVersion.getApiLevel()); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_WARNING); } } else { // looks like the min sdk is a codename, check it matches the codename // of the platform String codename = projectVersion.getCodename(); if (codename == null) { // platform is not a preview => fatal error String msg = String.format( "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (codename.equals(minSdkVersion) == false) { // platform and manifest codenames don't match => fatal error. String msg = String.format( "Value of manifest attribute '%1$s' does not match platform codename '%2$s'", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } } } if (javaPackage == null || javaPackage.length() == 0) { // looks like the AndroidManifest file isn't valid. String msg = String.format(Messages.s_Doesnt_Declare_Package_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses javaPackage (which is now guaranteed // to be null) will actually be executed or not. } // at this point we have the java package. We need to make sure it's not a different // package than the previous one that were built. if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) { // The manifest package has changed, the user may want to update // the launch configuration if (mManifestPackage != null) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Checking_Package_Change); FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage, javaPackage); flc.start(); } // now we delete the generated classes from their previous location deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS, mManifestPackage); deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS, mManifestPackage); // record the new manifest package, and save it. mManifestPackage = javaPackage; saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage); } if (mMustCompileResources) { // we need to figure out where to store the R class. // get the parent folder for R.java and update mManifestPackageSourceFolder IFolder packageFolder = getGenManifestPackageFolder(project); // get the resource folder IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES); // get the file system path IPath outputLocation = mGenFolder.getLocation(); IPath resLocation = resFolder.getLocation(); IPath manifestLocation = manifest == null ? null : manifest.getLocation(); // those locations have to exist for us to do something! if (outputLocation != null && resLocation != null && manifestLocation != null) { String osOutputPath = outputLocation.toOSString(); String osResPath = resLocation.toOSString(); String osManifestPath = manifestLocation.toOSString(); // remove the aapt markers removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE); removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Preparing_Generated_Files); // since the R.java file may be already existing in read-only // mode we need to make it readable so that aapt can overwrite // it IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS); // do the same for the Manifest.java class IFile manifestJavaFile = packageFolder.getFile( AndroidConstants.FN_MANIFEST_CLASS); // we actually need to delete the manifest.java as it may become empty and // in this case aapt doesn't generate an empty one, but instead doesn't // touch it. manifestJavaFile.delete(true, null); // launch aapt: create the command line ArrayList<String> array = new ArrayList<String>(); array.add(projectTarget.getPath(IAndroidTarget.AAPT)); array.add("package"); //$NON-NLS-1$ array.add("-m"); //$NON-NLS-1$ if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { array.add("-v"); //$NON-NLS-1$ } array.add("-J"); //$NON-NLS-1$ array.add(osOutputPath); array.add("-M"); //$NON-NLS-1$ array.add(osManifestPath); array.add("-S"); //$NON-NLS-1$ array.add(osResPath); array.add("-I"); //$NON-NLS-1$ array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR)); if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { StringBuilder sb = new StringBuilder(); for (String c : array) { sb.append(c); sb.append(' '); } String cmd_line = sb.toString(); AdtPlugin.printToConsole(project, cmd_line); } // launch int execError = 1; try { // launch the command line process Process process = Runtime.getRuntime().exec( array.toArray(new String[array.size()])); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process execError = grabProcessOutput(process, results); // attempt to parse the error output boolean parsingError = parseAaptOutput(results, project); // if we couldn't parse the output we display it in the console. if (parsingError) { if (execError != 0) { AdtPlugin.printErrorToConsole(project, results.toArray()); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL, project, results.toArray()); } } if (execError != 0) { // if the exec failed, and we couldn't parse the error output // (and therefore not all files that should have been marked, // were marked), we put a generic marker on the project and abort. if (parsingError) { markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR); } AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.AAPT_Error); // abort if exec failed. // This interrupts the build. The next builders will not run. stopBuild(Messages.AAPT_Error); } } catch (IOException e1) { // something happen while executing the process, // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } catch (InterruptedException e) { // we got interrupted waiting for the process to end... // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } // if the return code was OK, we refresh the folder that // contains R.java to force a java recompile. if (execError == 0) { // now add the R.java/Manifest.java to the list of file to be marked // as derived. mDerivedProgressMonitor.addFile(rJavaFile); mDerivedProgressMonitor.addFile(manifestJavaFile); // build has been done. reset the state of the builder mMustCompileResources = false; // and store it saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources); } } } else { // nothing to do } // now handle the aidl stuff. boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor); if (aidlStatus == false && mMustCompileResources == false) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Nothing_To_Compile); } } finally { // refresh the 'gen' source folder. Once this is done with the custom progress // monitor to mark all new files as derived mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor); } return null; }
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { try { mDerivedProgressMonitor.reset(); // First thing we do is go through the resource delta to not // lose it if we have to abort the build for any reason. // get the project objects IProject project = getProject(); // Top level check to make sure the build can move forward. abortOnBadSetup(project); IJavaProject javaProject = JavaCore.create(project); IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project); // now we need to get the classpath list ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); PreCompilerDeltaVisitor dv = null; String javaPackage = null; String minSdkVersion = null; if (kind == FULL_BUILD) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Pre_Compiler); mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Pre_Compiler); // Go through the resources and see if something changed. // Even if the mCompileResources flag is true from a previously aborted // build, we need to go through the Resource delta to get a possible // list of aidl files to compile/remove. IResourceDelta delta = getDelta(project); if (delta == null) { mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList); delta.accept(dv); // record the state mMustCompileResources |= dv.getCompileResources(); if (dv.getForceAidlCompile()) { buildAidlCompilationList(project, sourceFolderPathList); } else { // handle aidl modification, and update mMustCompileAidl mergeAidlFileModifications(dv.getAidlToCompile(), dv.getAidlToRemove()); } // get the java package from the visitor javaPackage = dv.getManifestPackage(); minSdkVersion = dv.getMinSdkVersion(); } } // store the build status in the persistent storage saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources); // if there was some XML errors, we just return w/o doing // anything since we've put some markers in the files anyway. if (dv != null && dv.mXmlError) { AdtPlugin.printErrorToConsole(project, Messages.Xml_Error); // This interrupts the build. The next builders will not run. stopBuild(Messages.Xml_Error); } // get the manifest file IFile manifest = AndroidManifestParser.getManifest(project); if (manifest == null) { String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses manifest (which is now guaranteed // to be null) will actually be executed or not. } // lets check the XML of the manifest first, if that hasn't been done by the // resource delta visitor yet. if (dv == null || dv.getCheckedManifestXml() == false) { BasicXmlErrorListener errorListener = new BasicXmlErrorListener(); AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest, errorListener); if (errorListener.mHasXmlError == true) { // there was an error in the manifest, its file has been marked, // by the XmlErrorHandler. // We return; String msg = String.format(Messages.s_Contains_Xml_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); // This interrupts the build. The next builders will not run. stopBuild(msg); } // get the java package from the parser javaPackage = parser.getPackage(); minSdkVersion = parser.getApiLevelRequirement(); } if (minSdkVersion != null) { int minSdkValue = -1; try { minSdkValue = Integer.parseInt(minSdkVersion); } catch (NumberFormatException e) { // it's ok, it means minSdkVersion contains a (hopefully) valid codename. } AndroidVersion projectVersion = projectTarget.getVersion(); if (minSdkValue != -1) { String codename = projectVersion.getCodename(); if (codename != null) { // integer minSdk when the target is a preview => fatal error String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (minSdkValue < projectVersion.getApiLevel()) { // integer minSdk is not high enough for the target => warning String msg = String.format( "Manifest min SDK version (%1$s) is lower than project target API level (%2$d)", minSdkVersion, projectVersion.getApiLevel()); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_WARNING); } } else { // looks like the min sdk is a codename, check it matches the codename // of the platform String codename = projectVersion.getCodename(); if (codename == null) { // platform is not a preview => fatal error String msg = String.format( "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (codename.equals(minSdkVersion) == false) { // platform and manifest codenames don't match => fatal error. String msg = String.format( "Value of manifest attribute '%1$s' does not match platform codename '%2$s'", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } } } else if (projectTarget.getVersion().isPreview()) { // else the minSdkVersion is not set but we are using a preview target. // Display an error String codename = projectTarget.getVersion().getCodename(); String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } if (javaPackage == null || javaPackage.length() == 0) { // looks like the AndroidManifest file isn't valid. String msg = String.format(Messages.s_Doesnt_Declare_Package_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses javaPackage (which is now guaranteed // to be null) will actually be executed or not. } // at this point we have the java package. We need to make sure it's not a different // package than the previous one that were built. if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) { // The manifest package has changed, the user may want to update // the launch configuration if (mManifestPackage != null) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Checking_Package_Change); FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage, javaPackage); flc.start(); } // now we delete the generated classes from their previous location deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS, mManifestPackage); deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS, mManifestPackage); // record the new manifest package, and save it. mManifestPackage = javaPackage; saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage); } if (mMustCompileResources) { // we need to figure out where to store the R class. // get the parent folder for R.java and update mManifestPackageSourceFolder IFolder packageFolder = getGenManifestPackageFolder(project); // get the resource folder IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES); // get the file system path IPath outputLocation = mGenFolder.getLocation(); IPath resLocation = resFolder.getLocation(); IPath manifestLocation = manifest == null ? null : manifest.getLocation(); // those locations have to exist for us to do something! if (outputLocation != null && resLocation != null && manifestLocation != null) { String osOutputPath = outputLocation.toOSString(); String osResPath = resLocation.toOSString(); String osManifestPath = manifestLocation.toOSString(); // remove the aapt markers removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE); removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Preparing_Generated_Files); // since the R.java file may be already existing in read-only // mode we need to make it readable so that aapt can overwrite // it IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS); // do the same for the Manifest.java class IFile manifestJavaFile = packageFolder.getFile( AndroidConstants.FN_MANIFEST_CLASS); // we actually need to delete the manifest.java as it may become empty and // in this case aapt doesn't generate an empty one, but instead doesn't // touch it. manifestJavaFile.delete(true, null); // launch aapt: create the command line ArrayList<String> array = new ArrayList<String>(); array.add(projectTarget.getPath(IAndroidTarget.AAPT)); array.add("package"); //$NON-NLS-1$ array.add("-m"); //$NON-NLS-1$ if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { array.add("-v"); //$NON-NLS-1$ } array.add("-J"); //$NON-NLS-1$ array.add(osOutputPath); array.add("-M"); //$NON-NLS-1$ array.add(osManifestPath); array.add("-S"); //$NON-NLS-1$ array.add(osResPath); array.add("-I"); //$NON-NLS-1$ array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR)); if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { StringBuilder sb = new StringBuilder(); for (String c : array) { sb.append(c); sb.append(' '); } String cmd_line = sb.toString(); AdtPlugin.printToConsole(project, cmd_line); } // launch int execError = 1; try { // launch the command line process Process process = Runtime.getRuntime().exec( array.toArray(new String[array.size()])); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process execError = grabProcessOutput(process, results); // attempt to parse the error output boolean parsingError = parseAaptOutput(results, project); // if we couldn't parse the output we display it in the console. if (parsingError) { if (execError != 0) { AdtPlugin.printErrorToConsole(project, results.toArray()); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL, project, results.toArray()); } } if (execError != 0) { // if the exec failed, and we couldn't parse the error output // (and therefore not all files that should have been marked, // were marked), we put a generic marker on the project and abort. if (parsingError) { markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR); } AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.AAPT_Error); // abort if exec failed. // This interrupts the build. The next builders will not run. stopBuild(Messages.AAPT_Error); } } catch (IOException e1) { // something happen while executing the process, // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } catch (InterruptedException e) { // we got interrupted waiting for the process to end... // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } // if the return code was OK, we refresh the folder that // contains R.java to force a java recompile. if (execError == 0) { // now add the R.java/Manifest.java to the list of file to be marked // as derived. mDerivedProgressMonitor.addFile(rJavaFile); mDerivedProgressMonitor.addFile(manifestJavaFile); // build has been done. reset the state of the builder mMustCompileResources = false; // and store it saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources); } } } else { // nothing to do } // now handle the aidl stuff. boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor); if (aidlStatus == false && mMustCompileResources == false) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Nothing_To_Compile); } } finally { // refresh the 'gen' source folder. Once this is done with the custom progress // monitor to mark all new files as derived mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor); } return null; }
diff --git a/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java b/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java index 5039466..cc824fa 100644 --- a/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java +++ b/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java @@ -1,183 +1,183 @@ package hudson.plugins.scm_sync_configuration; import hudson.model.Hudson; import hudson.model.User; import hudson.plugins.scm_sync_configuration.model.ScmContext; import hudson.plugins.scm_sync_configuration.strategies.ScmSyncStrategy; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.apache.maven.scm.manager.ScmManager; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.FileUtils; public class ScmSyncConfigurationBusiness { private static final String WORKING_DIRECTORY_PATH = "/scm-sync-configuration/"; private static final String CHECKOUT_SCM_DIRECTORY = "checkoutConfiguration"; private static final Logger LOGGER = Logger.getLogger(ScmSyncConfigurationBusiness.class.getName()); private boolean checkoutSucceeded; private SCMManipulator scmManipulator; private File checkoutScmDirectory = null; public ScmSyncConfigurationBusiness(){ } public void init(ScmContext scmContext) throws ComponentLookupException, PlexusContainerException { ScmManager scmManager = SCMManagerFactory.getInstance().createScmManager(); this.scmManipulator = new SCMManipulator(scmManager); this.checkoutScmDirectory = new File(getCheckoutScmDirectoryAbsolutePath()); this.checkoutSucceeded = false; initializeRepository(scmContext, false); } public void initializeRepository(ScmContext scmContext, boolean deleteCheckoutScmDir){ // Let's check if everything is available to checkout sources if(scmManipulator != null && scmManipulator.scmConfigurationSettledUp(scmContext, true)){ LOGGER.info("Initializing SCM repository for scm-sync-configuration plugin ..."); // If checkoutScmDirectory was not empty and deleteCheckoutScmDir is asked, reinitialize it ! if(deleteCheckoutScmDir){ cleanChekoutScmDirectory(); } // Creating checkout scm directory if(!checkoutScmDirectory.exists()){ try { FileUtils.forceMkdir(checkoutScmDirectory); LOGGER.info("Directory ["+ checkoutScmDirectory.getAbsolutePath() +"] created !"); } catch (IOException e) { LOGGER.warning("Directory ["+ checkoutScmDirectory.getAbsolutePath() +"] cannot be created !"); } } this.checkoutSucceeded = this.scmManipulator.checkout(this.checkoutScmDirectory); if(this.checkoutSucceeded){ LOGGER.info("SCM repository initialization done."); } } } public void cleanChekoutScmDirectory(){ if(checkoutScmDirectory.exists()){ LOGGER.info("Deleting old checkout SCM directory ..."); try { FileUtils.forceDelete(checkoutScmDirectory); } catch (IOException e) { LOGGER.throwing(FileUtils.class.getName(), "forceDelete", e); LOGGER.severe("Error while deleting ["+checkoutScmDirectory.getAbsolutePath()+"] : "+e.getMessage()); } this.checkoutSucceeded = false; } } public void deleteHierarchy(ScmContext scmContext, File rootHierarchy, User user){ deleteHierarchy(scmContext, rootHierarchy, createCommitMessage("Hierarchy deleted", user, null)); } public void deleteHierarchy(ScmContext scmContext, File rootHierarchy, String commitMessage){ if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){ return; } String rootHierarchyPathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(rootHierarchy); File rootHierarchyTranslatedInScm = new File(getCheckoutScmDirectoryAbsolutePath()+File.separator+rootHierarchyPathRelativeToHudsonRoot); scmManipulator.deleteHierarchy(rootHierarchyTranslatedInScm, commitMessage); } public void renameHierarchy(ScmContext scmContext, File oldDir, File newDir, User user){ if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){ return; } String oldDirPathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(oldDir); String newDirPathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(newDir); File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath()); String commitMessage = createCommitMessage("Moved "+oldDirPathRelativeToHudsonRoot+" hierarchy to "+newDirPathRelativeToHudsonRoot, user, null); LOGGER.info("Renaming hierarchy ["+oldDirPathRelativeToHudsonRoot+"] to ["+newDirPathRelativeToHudsonRoot+"]"); this.scmManipulator.renameHierarchy(scmRoot, oldDirPathRelativeToHudsonRoot, newDirPathRelativeToHudsonRoot, commitMessage); } public void synchronizeFile(ScmContext scmContext, File modifiedFile, String comment, User user){ if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){ return; } String modifiedFilePathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(modifiedFile); - LOGGER.info("Synchronizeing file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM ..."); + LOGGER.info("Synchronizing file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM ..."); String commitMessage = createCommitMessage("Modification on file", user, comment); File modifiedFileTranslatedInScm = new File(getCheckoutScmDirectoryAbsolutePath()+File.separator+modifiedFilePathRelativeToHudsonRoot); boolean modifiedFileAlreadySynchronized = modifiedFileTranslatedInScm.exists(); try { FileUtils.copyFile(modifiedFile, modifiedFileTranslatedInScm); } catch (IOException e) { LOGGER.throwing(FileUtils.class.getName(), "copyFile", e); LOGGER.severe("Error while copying file : "+e.getMessage()); return; } File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath()); List<File> synchronizedFiles = new ArrayList<File>(); // if modified file is not yet synchronized with scm, let's add it ! if(!modifiedFileAlreadySynchronized){ synchronizedFiles.addAll(this.scmManipulator.addFile(scmRoot, modifiedFilePathRelativeToHudsonRoot)); } else { synchronizedFiles.add(new File(modifiedFilePathRelativeToHudsonRoot)); } if(this.scmManipulator.checkinFiles(scmRoot, synchronizedFiles, commitMessage)){ LOGGER.info("Synchronized file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM !"); } } public void synchronizeAllConfigs(ScmContext scmContext, ScmSyncStrategy[] availableStrategies, User user){ List<File> filesToSync = new ArrayList<File>(); // Building synced files from strategies for(ScmSyncStrategy strategy : availableStrategies){ filesToSync.addAll(strategy.createInitializationSynchronizedFileset()); } for(File fileToSync : filesToSync){ String hudsonConfigPathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(fileToSync); File hudsonConfigTranslatedInScm = new File(getCheckoutScmDirectoryAbsolutePath()+File.separator+hudsonConfigPathRelativeToHudsonRoot); try { if(!hudsonConfigTranslatedInScm.exists() || !FileUtils.contentEquals(hudsonConfigTranslatedInScm, fileToSync)){ synchronizeFile(scmContext, fileToSync, "Synchronization init", user); } } catch (IOException e) { } } } public boolean scmCheckoutDirectorySettledUp(ScmContext scmContext){ return scmManipulator != null && this.scmManipulator.scmConfigurationSettledUp(scmContext, false) && this.checkoutSucceeded; } private static String createCommitMessage(String messagePrefix, User user, String comment){ StringBuilder commitMessage = new StringBuilder(); commitMessage.append(messagePrefix); if(user != null){ commitMessage.append(" by ").append(user.getId()); } if(comment != null){ commitMessage.append(" with following comment : ").append(comment); } return commitMessage.toString(); } private static String getCheckoutScmDirectoryAbsolutePath(){ return Hudson.getInstance().getRootDir().getAbsolutePath()+WORKING_DIRECTORY_PATH+CHECKOUT_SCM_DIRECTORY; } }
true
true
public void synchronizeFile(ScmContext scmContext, File modifiedFile, String comment, User user){ if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){ return; } String modifiedFilePathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(modifiedFile); LOGGER.info("Synchronizeing file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM ..."); String commitMessage = createCommitMessage("Modification on file", user, comment); File modifiedFileTranslatedInScm = new File(getCheckoutScmDirectoryAbsolutePath()+File.separator+modifiedFilePathRelativeToHudsonRoot); boolean modifiedFileAlreadySynchronized = modifiedFileTranslatedInScm.exists(); try { FileUtils.copyFile(modifiedFile, modifiedFileTranslatedInScm); } catch (IOException e) { LOGGER.throwing(FileUtils.class.getName(), "copyFile", e); LOGGER.severe("Error while copying file : "+e.getMessage()); return; } File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath()); List<File> synchronizedFiles = new ArrayList<File>(); // if modified file is not yet synchronized with scm, let's add it ! if(!modifiedFileAlreadySynchronized){ synchronizedFiles.addAll(this.scmManipulator.addFile(scmRoot, modifiedFilePathRelativeToHudsonRoot)); } else { synchronizedFiles.add(new File(modifiedFilePathRelativeToHudsonRoot)); } if(this.scmManipulator.checkinFiles(scmRoot, synchronizedFiles, commitMessage)){ LOGGER.info("Synchronized file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM !"); } }
public void synchronizeFile(ScmContext scmContext, File modifiedFile, String comment, User user){ if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){ return; } String modifiedFilePathRelativeToHudsonRoot = HudsonFilesHelper.buildPathRelativeToHudsonRoot(modifiedFile); LOGGER.info("Synchronizing file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM ..."); String commitMessage = createCommitMessage("Modification on file", user, comment); File modifiedFileTranslatedInScm = new File(getCheckoutScmDirectoryAbsolutePath()+File.separator+modifiedFilePathRelativeToHudsonRoot); boolean modifiedFileAlreadySynchronized = modifiedFileTranslatedInScm.exists(); try { FileUtils.copyFile(modifiedFile, modifiedFileTranslatedInScm); } catch (IOException e) { LOGGER.throwing(FileUtils.class.getName(), "copyFile", e); LOGGER.severe("Error while copying file : "+e.getMessage()); return; } File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath()); List<File> synchronizedFiles = new ArrayList<File>(); // if modified file is not yet synchronized with scm, let's add it ! if(!modifiedFileAlreadySynchronized){ synchronizedFiles.addAll(this.scmManipulator.addFile(scmRoot, modifiedFilePathRelativeToHudsonRoot)); } else { synchronizedFiles.add(new File(modifiedFilePathRelativeToHudsonRoot)); } if(this.scmManipulator.checkinFiles(scmRoot, synchronizedFiles, commitMessage)){ LOGGER.info("Synchronized file ["+modifiedFilePathRelativeToHudsonRoot+"] to SCM !"); } }
diff --git a/fr.imag.exschema/src/fr/imag/exschema/popup/actions/DiscoverAction.java b/fr.imag.exschema/src/fr/imag/exschema/popup/actions/DiscoverAction.java index 457b9e5..823d314 100644 --- a/fr.imag.exschema/src/fr/imag/exschema/popup/actions/DiscoverAction.java +++ b/fr.imag.exschema/src/fr/imag/exschema/popup/actions/DiscoverAction.java @@ -1,108 +1,108 @@ /* * Copyright 2012 jccastrejon * * This file is part of ExSchema. * * ExSchema 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 * any later version. * * ExSchema 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 ExSchema. If not, see <http://www.gnu.org/licenses/>. */ package fr.imag.exschema.popup.actions; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ITreeSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import fr.imag.exschema.Util; /** * Discover schemas action * * @author jccastrejon * */ public class DiscoverAction implements IObjectActionDelegate { /** * Eclipse shell. */ private Shell shell; /** * Current selected project. */ private IJavaProject project; /** * Default constructor. */ public DiscoverAction() { super(); } /** * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { this.shell = targetPart.getSite().getShell(); } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { String outputMessage; if (project != null) { try { Util.discoverSchemas(project); outputMessage = "The project schemas have been discovered"; } catch (Exception e) { e.printStackTrace(); - outputMessage = "An error ocurred while discovering the schemas"; + outputMessage = "An error ocurred while discovering the schemas: " + e.getMessage(); } } else { - outputMessage = "An error ocurred while discovering the schemas"; + outputMessage = "No project found to analyze for schemas"; } MessageDialog.openInformation(shell, "ExSchema", outputMessage); } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { Object selectedElement; IProject selectedProject; this.project = null; selectedElement = ((ITreeSelection) selection).getFirstElement(); if (IProject.class.isInstance(selectedElement)) { selectedProject = (IProject) selectedElement; try { if (selectedProject.isNatureEnabled("org.eclipse.jdt.core.javanature")) { this.project = JavaCore.create(selectedProject); } } catch (CoreException e) { } } } }
false
true
public void run(IAction action) { String outputMessage; if (project != null) { try { Util.discoverSchemas(project); outputMessage = "The project schemas have been discovered"; } catch (Exception e) { e.printStackTrace(); outputMessage = "An error ocurred while discovering the schemas"; } } else { outputMessage = "An error ocurred while discovering the schemas"; } MessageDialog.openInformation(shell, "ExSchema", outputMessage); }
public void run(IAction action) { String outputMessage; if (project != null) { try { Util.discoverSchemas(project); outputMessage = "The project schemas have been discovered"; } catch (Exception e) { e.printStackTrace(); outputMessage = "An error ocurred while discovering the schemas: " + e.getMessage(); } } else { outputMessage = "No project found to analyze for schemas"; } MessageDialog.openInformation(shell, "ExSchema", outputMessage); }
diff --git a/src/br/com/puc/sispol/interceptor/AutorizadorInterceptor.java b/src/br/com/puc/sispol/interceptor/AutorizadorInterceptor.java index 4d4821c..e6c2850 100644 --- a/src/br/com/puc/sispol/interceptor/AutorizadorInterceptor.java +++ b/src/br/com/puc/sispol/interceptor/AutorizadorInterceptor.java @@ -1,32 +1,32 @@ package br.com.puc.sispol.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class AutorizadorInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception { String uri = request.getRequestURI(); if (uri.endsWith("loginForm") || uri.endsWith("efetuaLogin") || uri.contains("resources") || uri.contains("mostraHome") - || uri.contains("novoUsuario") || uri.contains("apura") || uri.contains("lassificacaoSimulado") + || uri.contains("novoUsuario") || uri.contains("apura") || uri.contains("lassificacaoSimulado") ) { System.out.println("Carrega como usuário não logado"); return true; } if ((request.getSession().getAttribute("usuarioLogado") != null)) { System.out.println("Carrega como usuário logado"); return true; } System.out.println("Redireciana para a Home"); response.sendRedirect("mostraHome"); return false; } }
true
true
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception { String uri = request.getRequestURI(); if (uri.endsWith("loginForm") || uri.endsWith("efetuaLogin") || uri.contains("resources") || uri.contains("mostraHome") || uri.contains("novoUsuario") || uri.contains("apura") || uri.contains("lassificacaoSimulado") ) { System.out.println("Carrega como usuário não logado"); return true; } if ((request.getSession().getAttribute("usuarioLogado") != null)) { System.out.println("Carrega como usuário logado"); return true; } System.out.println("Redireciana para a Home"); response.sendRedirect("mostraHome"); return false; }
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception { String uri = request.getRequestURI(); if (uri.endsWith("loginForm") || uri.endsWith("efetuaLogin") || uri.contains("resources") || uri.contains("mostraHome") || uri.contains("novoUsuario") || uri.contains("apura") || uri.contains("lassificacaoSimulado") ) { System.out.println("Carrega como usuário não logado"); return true; } if ((request.getSession().getAttribute("usuarioLogado") != null)) { System.out.println("Carrega como usuário logado"); return true; } System.out.println("Redireciana para a Home"); response.sendRedirect("mostraHome"); return false; }
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RandomCommand.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RandomCommand.java index b67c28da3..93a10d7a2 100644 --- a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RandomCommand.java +++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RandomCommand.java @@ -1,117 +1,117 @@ package net.aufdemrand.denizen.scripts.commands.core; import java.util.ArrayList; import java.util.LinkedHashMap; import net.aufdemrand.denizen.exceptions.CommandExecutionException; import net.aufdemrand.denizen.exceptions.InvalidArgumentsException; import net.aufdemrand.denizen.scripts.ScriptEntry; import net.aufdemrand.denizen.scripts.queues.ScriptQueue; import net.aufdemrand.denizen.scripts.commands.BracedCommand; import net.aufdemrand.denizen.utilities.Utilities; import net.aufdemrand.denizen.objects.aH; import net.aufdemrand.denizen.utilities.debugging.dB; /** * Randomly selects a random script entry from the proceeding entries, discards * the rest. * * <ol><tt>Usage: RANDOM [#]</tt></ol> * * [#] of entries to randomly select from. Will select 1 of # to execute and * discard the rest.<br/><br/> * * Example Usage:<br/> * <ul style="list-style-type: none;"> * <li><tt>Script:</tt></li> * <li><tt>- RANDOM 3</tt></li> * <li><tt>- CHAT Random Message 1</tt></li> * <li><tt>- CHAT Random Message 2</tt></li> * <li><tt>- CHAT Random Message 3 </tt></li> * </ul> * * @author Jeremy Schroeder */ public class RandomCommand extends BracedCommand { @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) { if (arg.matches("{")) { scriptEntry.addObject("braces", getBracedCommands(scriptEntry, 0)); break; } else if (!scriptEntry.hasObject("possibilities") && arg.matchesPrimitive(aH.PrimitiveType.Integer)) scriptEntry.addObject("possibilities", arg.asElement()); else arg.reportUnhandled(); } if (!scriptEntry.hasObject("braces")) { if (!scriptEntry.hasObject("possibilities")) throw new InvalidArgumentsException("Missing possibilities!"); if (scriptEntry.getElement("possibilities").asInt() <= 1) throw new InvalidArgumentsException("Must randomly select more than one item."); if (scriptEntry.getResidingQueue().getQueueSize() < scriptEntry.getElement("possibilities").asInt()) throw new InvalidArgumentsException("Invalid Size! Random # must not be larger than the script!"); } } @SuppressWarnings("unchecked") @Override public void execute(ScriptEntry scriptEntry) throws CommandExecutionException { // TODO: ADD REPORT! int possibilities = 0; ScriptQueue queue = scriptEntry.getResidingQueue(); ArrayList<ScriptEntry> bracedCommands = null; if (!scriptEntry.hasObject("braces")) { possibilities = scriptEntry.getElement("possibilities").asInt(); } else { bracedCommands = ((LinkedHashMap<String, ArrayList<ScriptEntry>>) scriptEntry.getObject("braces")).get("RANDOM"); possibilities = bracedCommands.size(); } int selected = Utilities.getRandom().nextInt(possibilities); - dB.echoDebug(scriptEntry, "...random number generator selected '" + String.valueOf(selected + 1) + "'."); + dB.report(scriptEntry, getName(), aH.debugObj("possibilities", possibilities) + aH.debugObj("choice", selected + 1)); if (bracedCommands == null) { ScriptEntry keeping = null; for (int x = 0; x < possibilities; x++) { if (x != selected) queue.removeEntry(0); else { dB.echoDebug(scriptEntry, "...selected '" + queue.getEntry(0).getCommandName() + ": " + queue.getEntry(0).getArguments() + "'."); keeping = queue.getEntry(0); queue.removeEntry(0); } } queue.injectEntry(keeping, 0); } else { - queue.injectEntry(bracedCommands.get(selected), 0); + queue.injectEntry(bracedCommands.get(selected).addObject("reqID", scriptEntry.getObject("reqID")), 0); } } }
false
true
public void execute(ScriptEntry scriptEntry) throws CommandExecutionException { // TODO: ADD REPORT! int possibilities = 0; ScriptQueue queue = scriptEntry.getResidingQueue(); ArrayList<ScriptEntry> bracedCommands = null; if (!scriptEntry.hasObject("braces")) { possibilities = scriptEntry.getElement("possibilities").asInt(); } else { bracedCommands = ((LinkedHashMap<String, ArrayList<ScriptEntry>>) scriptEntry.getObject("braces")).get("RANDOM"); possibilities = bracedCommands.size(); } int selected = Utilities.getRandom().nextInt(possibilities); dB.echoDebug(scriptEntry, "...random number generator selected '" + String.valueOf(selected + 1) + "'."); if (bracedCommands == null) { ScriptEntry keeping = null; for (int x = 0; x < possibilities; x++) { if (x != selected) queue.removeEntry(0); else { dB.echoDebug(scriptEntry, "...selected '" + queue.getEntry(0).getCommandName() + ": " + queue.getEntry(0).getArguments() + "'."); keeping = queue.getEntry(0); queue.removeEntry(0); } } queue.injectEntry(keeping, 0); } else { queue.injectEntry(bracedCommands.get(selected), 0); } }
public void execute(ScriptEntry scriptEntry) throws CommandExecutionException { // TODO: ADD REPORT! int possibilities = 0; ScriptQueue queue = scriptEntry.getResidingQueue(); ArrayList<ScriptEntry> bracedCommands = null; if (!scriptEntry.hasObject("braces")) { possibilities = scriptEntry.getElement("possibilities").asInt(); } else { bracedCommands = ((LinkedHashMap<String, ArrayList<ScriptEntry>>) scriptEntry.getObject("braces")).get("RANDOM"); possibilities = bracedCommands.size(); } int selected = Utilities.getRandom().nextInt(possibilities); dB.report(scriptEntry, getName(), aH.debugObj("possibilities", possibilities) + aH.debugObj("choice", selected + 1)); if (bracedCommands == null) { ScriptEntry keeping = null; for (int x = 0; x < possibilities; x++) { if (x != selected) queue.removeEntry(0); else { dB.echoDebug(scriptEntry, "...selected '" + queue.getEntry(0).getCommandName() + ": " + queue.getEntry(0).getArguments() + "'."); keeping = queue.getEntry(0); queue.removeEntry(0); } } queue.injectEntry(keeping, 0); } else { queue.injectEntry(bracedCommands.get(selected).addObject("reqID", scriptEntry.getObject("reqID")), 0); } }
diff --git a/cadpage/src/net/anei/cadpage/C2DMReceiver.java b/cadpage/src/net/anei/cadpage/C2DMReceiver.java index a4cd3c7f6..fbdec9ce7 100644 --- a/cadpage/src/net/anei/cadpage/C2DMReceiver.java +++ b/cadpage/src/net/anei/cadpage/C2DMReceiver.java @@ -1,264 +1,265 @@ /* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.anei.cadpage; import net.anei.cadpage.HttpService.HttpRequest; import net.anei.cadpage.donation.DonationManager; import net.anei.cadpage.parsers.SmsMsgParser; import net.anei.cadpage.vendors.VendorManager; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; /** * Receives M2DM related intents */ public class C2DMReceiver extends BroadcastReceiver { private static final String ACTION_C2DM_REGISTER = "com.google.android.c2dm.intent.REGISTER"; private static final String ACTION_C2DM_UNREGISTER = "com.google.android.c2dm.intent.UNREGISTER"; private static final String ACTION_C2DM_REGISTERED = "com.google.android.c2dm.intent.REGISTRATION"; private static final String ACTION_C2DM_RECEIVE = "com.google.android.c2dm.intent.RECEIVE"; private static final String C2DM_SENDER_EMAIL = "[email protected]"; private static Activity curActivity = null; @Override public void onReceive(Context context, Intent intent) { if (Log.DEBUG) Log.v("C2DMReceiver: onReceive()"); // If initialization failure in progress, shut down without doing anything if (TopExceptionHandler.isInitFailure()) return; // Free version doesn't do C2DM stuff if (DonationManager.instance().isFreeVersion()) return; if (ACTION_C2DM_REGISTERED.equals(intent.getAction())) { handleRegistration(context, intent); } else if (ACTION_C2DM_RECEIVE.equals(intent.getAction())) { handleMessage(context, intent); } } private void handleRegistration(Context context, Intent intent) { String error = intent.getStringExtra("error"); if (error != null) { Log.w("C2DM registration failed: " + error); ManagePreferences.setRegistrationId(null); VendorManager.instance().failureC2DMId(context, error); return; } String regId = intent.getStringExtra("unregistered"); if (regId != null) { Log.w("C2DM registration cancelled: " + regId); ManagePreferences.setRegistrationId(null); VendorManager.instance().unregisterC2DMId(context, regId); return; } regId = intent.getStringExtra("registration_id"); if (regId != null) { Log.w("C2DM registration succeeded: " + regId); ManagePreferences.setRegistrationId(regId); VendorManager.instance().registerC2DMId(context, regId); return; } } private void handleMessage(final Context context, final Intent intent) { // If registration has been canceled, all C2DM messages should be ignored if (ManagePreferences.registrationId() == null) return; // See what kind of message this is String type = intent.getStringExtra("type"); + if (type == null) type = "PAGE"; // Ping just needs to be acknowledged if (type.equals("PING")) { sendAutoAck(context, intent); return; } // Register and unregister requests are handled by VendorManager if (type.equals("REGISTER") || type.equals("UNREGISTER")) { String vendor = intent.getStringExtra("vendor"); String account = intent.getStringExtra("account"); String token = intent.getStringExtra("token"); VendorManager.instance().vendorRequest(context, type, vendor, account, token); sendAutoAck(context, intent); return; } // Save timestamp final long timestamp = System.currentTimeMillis(); // Retrieve message content from intent for from URL String content = intent.getStringExtra("content"); if (content != null) { processContent(context, intent, content, timestamp); sendAutoAck(context, intent); return; } String contentURL = intent.getStringExtra("content_url"); if (contentURL != null) { HttpService.addHttpRequest(context, new HttpRequest(Uri.parse(contentURL)){ @Override public void processResponse(int status, String result) { if (status % 100 == 2) { processContent(context, intent, result, timestamp); } } }); return; } Log.w("C2DM message has no content"); } /** * Send auto acknowledgment when message is received * @param context current context * @param intent received intent */ private void sendAutoAck(Context context, Intent intent) { String ackURL = intent.getStringExtra("ack_url"); sendResponseMsg(context, ackURL, "auto"); } private void processContent(Context context, Intent intent, String content, long timestamp) { // Reconstruct message from data from intent fields String from = intent.getStringExtra("from"); if (from == null) from = "C2DM"; String subject = intent.getStringExtra("subject"); if (subject == null) subject = ""; String location = intent.getStringExtra("format"); if (location != null) { if (location.equals("Active911")) location = "Cadpage"; location = ManagePreferences.convertOldLocationCode(context, location); } String sponsor = intent.getStringExtra("sponsor"); // Get the acknowledge URL and request code String ackURL = intent.getStringExtra("ack_url"); String ackReq = intent.getStringExtra("ack_req"); if (ackURL == null) ackReq = null; if (ackReq == null) ackReq = ""; SmsMmsMessage message = new SmsMmsMessage(from, subject, content, timestamp, location, sponsor, ackReq, ackURL); // Add to log buffer if (!SmsMsgLogBuffer.getInstance().add(message)) return; // See if the current parser will accept this as a CAD page boolean isPage = message.isPageMsg(true, false); // If it didn't, accept it as a general page. We have to do something with // it or it will just disappear if (! isPage) { SmsMsgParser genAlertParser = ManageParsers.getInstance().getAlertParser(); isPage = genAlertParser.isPageMsg(message, true, true); } // This should never happen, but if the general alert parser can't handle // it bail out if (!isPage) return; SmsReceiver.processCadPage(context, message); } /** * Register activity to be used to generate any alert dialogs * @param activity */ public static void registerActivity(Activity activity) { curActivity = activity; } /** * Unregister activity previously registered for any generated alert dialogs * @param activity */ public static void unregisterActivity(Activity activity) { if (curActivity == activity) curActivity = null; } /** * send response messages * @param context current context * @param ackURL acknowledge URL * @param type request type to be sent */ public static void sendResponseMsg(Context context, String ackURL, String type) { if (ackURL == null) return; Uri uri = Uri.parse(ackURL).buildUpon().appendQueryParameter("type", type).build(); HttpService.addHttpRequest(context, new HttpRequest(uri)); } /** * Request a new C2DM registration ID * @param context current context */ public static void register(Context context) { Intent intent = new Intent(ACTION_C2DM_REGISTER); intent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0)); intent.putExtra("sender", C2DM_SENDER_EMAIL); context.startService(intent); } /** * Request that current C2DM registration be dropped * @param context current context */ public static void unregister(Context context) { Intent intent = new Intent(ACTION_C2DM_UNREGISTER); intent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0)); context.startService(intent); } /** * Generate an Email message with the current registration ID * @param context current context */ public static void emailRegistrationId(Context context) { // Build send email intent and launch it Intent intent = new Intent(Intent.ACTION_SEND); String emailSubject = CadPageApplication.getNameVersion() + " C2DM registrion ID"; intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject); intent.putExtra(Intent.EXTRA_TEXT, "My C2DM registration ID is " + ManagePreferences.registrationId()); intent.setType("message/rfc822"); context.startActivity(Intent.createChooser( intent, context.getString(R.string.pref_sendemail_title))); } }
true
true
private void handleMessage(final Context context, final Intent intent) { // If registration has been canceled, all C2DM messages should be ignored if (ManagePreferences.registrationId() == null) return; // See what kind of message this is String type = intent.getStringExtra("type"); // Ping just needs to be acknowledged if (type.equals("PING")) { sendAutoAck(context, intent); return; } // Register and unregister requests are handled by VendorManager if (type.equals("REGISTER") || type.equals("UNREGISTER")) { String vendor = intent.getStringExtra("vendor"); String account = intent.getStringExtra("account"); String token = intent.getStringExtra("token"); VendorManager.instance().vendorRequest(context, type, vendor, account, token); sendAutoAck(context, intent); return; } // Save timestamp final long timestamp = System.currentTimeMillis(); // Retrieve message content from intent for from URL String content = intent.getStringExtra("content"); if (content != null) { processContent(context, intent, content, timestamp); sendAutoAck(context, intent); return; } String contentURL = intent.getStringExtra("content_url"); if (contentURL != null) { HttpService.addHttpRequest(context, new HttpRequest(Uri.parse(contentURL)){ @Override public void processResponse(int status, String result) { if (status % 100 == 2) { processContent(context, intent, result, timestamp); } } }); return; } Log.w("C2DM message has no content"); }
private void handleMessage(final Context context, final Intent intent) { // If registration has been canceled, all C2DM messages should be ignored if (ManagePreferences.registrationId() == null) return; // See what kind of message this is String type = intent.getStringExtra("type"); if (type == null) type = "PAGE"; // Ping just needs to be acknowledged if (type.equals("PING")) { sendAutoAck(context, intent); return; } // Register and unregister requests are handled by VendorManager if (type.equals("REGISTER") || type.equals("UNREGISTER")) { String vendor = intent.getStringExtra("vendor"); String account = intent.getStringExtra("account"); String token = intent.getStringExtra("token"); VendorManager.instance().vendorRequest(context, type, vendor, account, token); sendAutoAck(context, intent); return; } // Save timestamp final long timestamp = System.currentTimeMillis(); // Retrieve message content from intent for from URL String content = intent.getStringExtra("content"); if (content != null) { processContent(context, intent, content, timestamp); sendAutoAck(context, intent); return; } String contentURL = intent.getStringExtra("content_url"); if (contentURL != null) { HttpService.addHttpRequest(context, new HttpRequest(Uri.parse(contentURL)){ @Override public void processResponse(int status, String result) { if (status % 100 == 2) { processContent(context, intent, result, timestamp); } } }); return; } Log.w("C2DM message has no content"); }
diff --git a/jcommune/jcommune-model/src/main/java/org/jtalks/jcommune/model/dao/hibernate/TopicHibernateDao.java b/jcommune/jcommune-model/src/main/java/org/jtalks/jcommune/model/dao/hibernate/TopicHibernateDao.java index a872afe2..0072f8e0 100644 --- a/jcommune/jcommune-model/src/main/java/org/jtalks/jcommune/model/dao/hibernate/TopicHibernateDao.java +++ b/jcommune/jcommune-model/src/main/java/org/jtalks/jcommune/model/dao/hibernate/TopicHibernateDao.java @@ -1,69 +1,69 @@ /** * Copyright (C) 2011 jtalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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 * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * Also add information on how to contact you by electronic and paper mail. * Creation date: Apr 12, 2011 / 8:05:19 PM * The jtalks.org Project */ package org.jtalks.jcommune.model.dao.hibernate; import org.jtalks.jcommune.model.dao.TopicDao; import org.jtalks.jcommune.model.entity.Topic; import java.util.List; /** * Hibernate DAO implementation from the {@link Topic}. * * @author Pavel Vervenko * @author Kirill Afonin * @author Vitaliy Kravchenko */ public class TopicHibernateDao extends AbstractHibernateDao<Topic> implements TopicDao { /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<Topic> getTopicRangeInBranch(Long branchId, int start, int max) { return getSession().getNamedQuery("getAllTopicsInBranch") .setLong("branchId", branchId) .setFirstResult(start) .setMaxResults(max) .list(); } /** * {@inheritDoc} */ @Override public int getTopicsInBranchCount(long branchId) { return ((Number) getSession().createQuery("select count(*) from Topic t where t.branch = ?") .setLong(0, branchId).uniqueResult()).intValue(); } /** * {@inheritDoc} */ @Override public boolean delete(Long id) { - //TODO: not efficient solution + //TODO: not efficient solution. See more info on the next link http://bit.ly/m85eLs Topic topic = get(id); if (topic == null) return false; getSession().delete(topic); return true; } }
true
true
public boolean delete(Long id) { //TODO: not efficient solution Topic topic = get(id); if (topic == null) return false; getSession().delete(topic); return true; }
public boolean delete(Long id) { //TODO: not efficient solution. See more info on the next link http://bit.ly/m85eLs Topic topic = get(id); if (topic == null) return false; getSession().delete(topic); return true; }
diff --git a/src/com/gdg/andconlab/models/Speaker.java b/src/com/gdg/andconlab/models/Speaker.java index f211928..20022b4 100755 --- a/src/com/gdg/andconlab/models/Speaker.java +++ b/src/com/gdg/andconlab/models/Speaker.java @@ -1,98 +1,99 @@ package com.gdg.andconlab.models; import java.io.Serializable; import org.codehaus.jackson.annotate.JsonProperty; import android.content.ContentValues; import android.database.Cursor; import com.gdg.andconlab.StringUtils; public class Speaker implements Serializable { private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "speakers"; public static final String COLUMN_NAME_ID = "_id"; public static final String COLUMN_NAME_BIO = "bio"; public static final String COLUMN_FIRST_NAME = "first_name"; public static final String COLUMN_LAST_NAME = "last_name"; public static final String COLUMN_NAME_IMAGE_URL = "image_url"; ////////////////////////////////////////// // Members ////////////////////////////////////////// @JsonProperty("id") private long mId; @JsonProperty("bio") private String mBio; @JsonProperty("first_name") private String mFirstName; @JsonProperty("last_name") private String mLastName; @JsonProperty("image_url") private String mImageUrl; public ContentValues getContentValues() { ContentValues cv = new ContentValues(); cv.put(COLUMN_FIRST_NAME, mFirstName); cv.put(COLUMN_LAST_NAME, mLastName); cv.put(COLUMN_NAME_BIO, mBio); cv.put(COLUMN_NAME_IMAGE_URL, mImageUrl); + cv.put(COLUMN_NAME_ID, mId); return cv; } public void buildFromCursor (Cursor c) { mId = c.getLong(c.getColumnIndex(COLUMN_NAME_ID)); mBio = c.getString(c.getColumnIndex(COLUMN_NAME_BIO)); mFirstName = c.getString(c.getColumnIndex(COLUMN_FIRST_NAME)); mLastName = c.getString(c.getColumnIndex(COLUMN_LAST_NAME)); mImageUrl = c.getString(c.getColumnIndex(COLUMN_NAME_IMAGE_URL)); } ////////////////////////////////////////// // Getters & Setters ////////////////////////////////////////// public String getBio() { return this.mBio; } public void setBio(String bio) { this.mBio = bio; } public String getFirstName() { return this.mFirstName; } public void setFirstName(String firstName) { this.mFirstName = firstName; } public long getId() { return this.mId; } public void setId(long id) { this.mId = id; } public String getImageUrl() { return this.mImageUrl; } public void setImageUrl(String imageUrl) { this.mImageUrl = imageUrl; } public String getLastName() { return this.mLastName; } public void setLastName(String lastName) { this.mLastName = lastName; } public String getFullName() { return StringUtils.concat(mFirstName, " ", mLastName); } }
true
true
public ContentValues getContentValues() { ContentValues cv = new ContentValues(); cv.put(COLUMN_FIRST_NAME, mFirstName); cv.put(COLUMN_LAST_NAME, mLastName); cv.put(COLUMN_NAME_BIO, mBio); cv.put(COLUMN_NAME_IMAGE_URL, mImageUrl); return cv; }
public ContentValues getContentValues() { ContentValues cv = new ContentValues(); cv.put(COLUMN_FIRST_NAME, mFirstName); cv.put(COLUMN_LAST_NAME, mLastName); cv.put(COLUMN_NAME_BIO, mBio); cv.put(COLUMN_NAME_IMAGE_URL, mImageUrl); cv.put(COLUMN_NAME_ID, mId); return cv; }
diff --git a/src/usask/hci/fastdraw/DrawView.java b/src/usask/hci/fastdraw/DrawView.java index 331026c..f9226c8 100644 --- a/src/usask/hci/fastdraw/DrawView.java +++ b/src/usask/hci/fastdraw/DrawView.java @@ -1,846 +1,847 @@ package usask.hci.fastdraw; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import usask.hci.fastdraw.GestureDetector.Gesture; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.NumberPicker; public class DrawView extends View { private MainActivity mMainActivity; private StudyLogger mLog; private StudyController mStudyCtl; private boolean mStudyMode; private Bitmap mBitmap; private Paint mBitmapPaint; private final int mCols = 4; private final int mRows = 5; private float mColWidth; private float mRowHeight; private boolean mShowOverlay; private long mOverlayStart; private Paint mPaint; private int mSelected; private long mPressedInsideTime; private int mFingerInside; private boolean mCheckOverlay; private Set<Integer> mFingers; private Set<Integer> mIgnoredFingers; private Selection[] mSelections; private HashMap<Gesture, Integer> mGestureSelections; private Tool mTool; private int mColor; private int mThickness; private String mToolName; private String mColorName; private String mThicknessName; private Bitmap mUndo; private Bitmap mNextUndo; private boolean mLeftHanded; private final float mThreshold = 10; // pixel distance before tool registers private SparseArray<PointF> mOrigins; private boolean mPermanentGrid; private Rect mTextBounds; private SparseArray<Long> mFlashTimes; private SparseArray<Long> mRecentTouches; private boolean mChanged; private GestureDetector mGestureDetector; private Gesture mGesture; private int mPossibleGestureFinger; private long mPossibleGestureFingerTime; private int mGestureFinger; private PointF mGestureFingerPos; private boolean mShowGestureMenu; private Gesture mActiveCategory; private PointF mActiveCategoryOrigin; private Gesture mSubSelection; private UI mUI; private final int mChordDelay = 1000 * 1000 * 200; // 200ms in ns private final int mFlashDelay = 1000 * 1000 * 400; // 400ms in ns private final int mGestureMenuDelay = 1000 * 1000 * 200; // 200ms in ns private final int mOverlayButtonIndex = 16; private final int mGestureButtonDist = 150; private final int mGestureButtonSize = 75; private enum UI { CHORD, GESTURE } private enum Action { SAVE, CLEAR, UNDO } private enum SelectionType { TOOL, COLOR, THICKNESS, ACTION } private class Selection { public Object object; public String name; public SelectionType type; public Selection(Object object, String name, SelectionType type) { this.object = object; this.name = name; this.type = type; } } public DrawView(Context mainActivity) { super(mainActivity); if (!(mainActivity instanceof MainActivity)) { Log.e("DrawView", "DrawView was not given the MainActivity"); return; } mUI = UI.CHORD; mMainActivity = (MainActivity) mainActivity; mStudyMode = false; mLog = new StudyLogger(mainActivity); mBitmapPaint = new Paint(Paint.DITHER_FLAG); mPaint = new Paint(); mPaint.setTextSize(26); mPaint.setTextAlign(Align.CENTER); mSelected = -1; mFingerInside = -1; mCheckOverlay = true; mFingers = new HashSet<Integer>(); mIgnoredFingers = new HashSet<Integer>(); mLeftHanded = false; mPermanentGrid = false; mOrigins = new SparseArray<PointF>(); mTextBounds = new Rect(); mFlashTimes = new SparseArray<Long>(); mRecentTouches = new SparseArray<Long>(); mChanged = false; mGestureDetector = new GestureDetector(); mGesture = Gesture.UNKNOWN; mGestureFinger = -1; mPossibleGestureFinger = -1; mShowGestureMenu = false; mActiveCategory = Gesture.UNKNOWN; mActiveCategoryOrigin = new PointF(); mSubSelection = Gesture.UNKNOWN; mSelections = new Selection[] { new Selection(new PaintTool(this), "Paintbrush", SelectionType.TOOL), new Selection(new LineTool(this), "Line", SelectionType.TOOL), new Selection(new CircleTool(this), "Circle", SelectionType.TOOL), new Selection(new RectangleTool(this), "Rectangle", SelectionType.TOOL), new Selection(Color.BLACK, "Black", SelectionType.COLOR), new Selection(Color.RED, "Red", SelectionType.COLOR), new Selection(Color.GREEN, "Green", SelectionType.COLOR), new Selection(Color.BLUE, "Blue", SelectionType.COLOR), new Selection(Color.WHITE, "White", SelectionType.COLOR), new Selection(Color.YELLOW, "Yellow", SelectionType.COLOR), new Selection(Color.CYAN, "Cyan", SelectionType.COLOR), new Selection(Color.MAGENTA, "Magenta", SelectionType.COLOR), new Selection(1, "Fine", SelectionType.THICKNESS), new Selection(6, "Thin", SelectionType.THICKNESS), new Selection(16, "Normal", SelectionType.THICKNESS), new Selection(50, "Wide", SelectionType.THICKNESS), null, // The position of the command map button new Selection(Action.SAVE, "Save", SelectionType.ACTION), new Selection(Action.CLEAR, "Clear", SelectionType.ACTION), new Selection(Action.UNDO, "Undo", SelectionType.ACTION) }; mGestureSelections = new HashMap<Gesture, Integer>(); mGestureSelections.put(Gesture.UP, 0); // Paintbrush mGestureSelections.put(Gesture.UP_RIGHT, 1); // Line mGestureSelections.put(Gesture.UP_DOWN, 2); // Circle mGestureSelections.put(Gesture.UP_LEFT, 3); // Rectangle mGestureSelections.put(Gesture.LEFT, 4); // Black mGestureSelections.put(Gesture.LEFT_UP, 5); // Red mGestureSelections.put(Gesture.LEFT_RIGHT, 6); // Green mGestureSelections.put(Gesture.LEFT_DOWN, 7); // Blue mGestureSelections.put(Gesture.RIGHT, 8); // White mGestureSelections.put(Gesture.RIGHT_DOWN, 9); // Yellow mGestureSelections.put(Gesture.RIGHT_LEFT, 10); // Cyan mGestureSelections.put(Gesture.RIGHT_UP, 11); // Magenta mGestureSelections.put(Gesture.DOWN_LEFT, 12); // Fine mGestureSelections.put(Gesture.DOWN_UP, 13); // Thin mGestureSelections.put(Gesture.DOWN, 14); // Normal mGestureSelections.put(Gesture.DOWN_RIGHT, 15); // Wide // Default to thin black paintbrush changeSelection(0, false); changeSelection(4, false); changeSelection(13, false); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { long now = System.nanoTime(); if (mUI == UI.CHORD) { synchronized (mFlashTimes) { for (int i = 0; i < mFlashTimes.size(); i++) { long time = mFlashTimes.valueAt(i); if (now - time > mFlashDelay) { mFlashTimes.removeAt(i); postInvalidate(); } } } if (mFingerInside != -1 && now - mPressedInsideTime > mChordDelay && mCheckOverlay && !mShowOverlay) { mOverlayStart = now; mShowOverlay = true; mLog.event("Overlay shown"); mTool.clearFingers(); postInvalidate(); if (mStudyMode) mStudyCtl.handleOverlayShown(); } } else if (mUI == UI.GESTURE) { if (mPossibleGestureFinger != -1 && now - mPossibleGestureFingerTime > mGestureMenuDelay && !mChanged) { mGestureFinger = mPossibleGestureFinger; mIgnoredFingers.add(mGestureFinger); mPossibleGestureFinger = -1; mShowGestureMenu = true; postInvalidate(); } } } }, 25, 25); final CheckBox studyCheckBox = new CheckBox(mainActivity); studyCheckBox.setText("Run in study mode"); studyCheckBox.setChecked(true); final CheckBox gestureCheckBox = new CheckBox(mainActivity); gestureCheckBox.setText("Use the gesture interface"); final NumberPicker subjectIdPicker = new NumberPicker(mainActivity); subjectIdPicker.setMinValue(0); subjectIdPicker.setMaxValue(999); subjectIdPicker.setWrapSelectorWheel(false); // Prevent the keyboard from popping up. subjectIdPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); LinearLayout studySetupView = new LinearLayout(mainActivity); studySetupView.setOrientation(LinearLayout.VERTICAL); studySetupView.addView(studyCheckBox); studySetupView.addView(gestureCheckBox); studySetupView.addView(subjectIdPicker); new AlertDialog.Builder(mainActivity) .setMessage(R.string.dialog_study_mode) .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mStudyMode = studyCheckBox.isChecked(); if (mStudyMode) { mStudyCtl = new StudyController(mLog); mMainActivity.setTitle(mStudyCtl.getPrompt()); } mLog.setSubjectId(subjectIdPicker.getValue()); mUI = gestureCheckBox.isChecked() ? UI.GESTURE : UI.CHORD; DrawView.this.invalidate(); } }) .setView(studySetupView) .show(); } public int getColor() { return mColor; } public int getThickness() { return mThickness; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mBitmap); canvas.drawRGB(0xFF, 0xFF, 0xFF); mColWidth = (float)w / mCols; mRowHeight = (float)h / mRows; } private RectF getButtonBounds(int index) { int y = index / mCols; int x = index % mCols; if (mLeftHanded) x = mCols - x - 1; float top = mRowHeight * y; float bottom = top + mRowHeight; float left = mColWidth * x; float right = left + mColWidth; return new RectF(left, top, right, bottom); } private RectF getOverlayButtonBounds() { return getButtonBounds(mOverlayButtonIndex); } @Override protected void onDraw(Canvas canvas) { RectF bounds = getOverlayButtonBounds(); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); mTool.draw(canvas); if (mShowOverlay) canvas.drawARGB(0xAA, 0xFF, 0xFF, 0xFF); if (mUI == UI.CHORD) { mPaint.setColor(0x88FFFF00); canvas.drawRect(bounds, mPaint); } if (mShowOverlay || (mPermanentGrid && mUI == UI.CHORD)) { mPaint.setColor(0x44666666); for (int i = 0; i < mRows; i++) { float top = i * mRowHeight; canvas.drawLine(0, top, mColWidth * mCols, top, mPaint); } for (int i = 0; i < mCols; i++) { float left = i * mColWidth; canvas.drawLine(left, 0, left, mRowHeight * mRows, mPaint); } } if (mShowOverlay) { mPaint.setColor(0xFF000000); for (int y = 0; y < mRows; y++) { for (int x = 0; x < mCols; x++) { int realX = x; if (mLeftHanded) realX = mCols - x - 1; int i = y * mCols + realX; if (mSelections[i] != null) { String name = mSelections[i].name; int heightAdj = getTextHeight(name, mPaint) / 2; canvas.drawText(name, (x + 0.5f) * mColWidth, (y + 0.5f) * mRowHeight + heightAdj, mPaint); } } } } else if (!mPermanentGrid && mUI == UI.CHORD) { mPaint.setColor(0x44666666); canvas.drawLine(bounds.left, bounds.top, bounds.right, bounds.top, mPaint); if (mLeftHanded) canvas.drawLine(bounds.left, bounds.top, bounds.left, bounds.bottom, mPaint); else canvas.drawLine(bounds.right, bounds.top, bounds.right, bounds.bottom, mPaint); } if (mUI == UI.CHORD) { synchronized (mFlashTimes) { for (int i = 0; i < mFlashTimes.size(); i++) { int selectionNum = mFlashTimes.keyAt(i); Selection selection = mSelections[selectionNum]; if (selection != null) { RectF buttonBounds = getButtonBounds(selectionNum); mPaint.setColor(0xBBF5F5F5); canvas.drawRect(buttonBounds, mPaint); mPaint.setColor(0x44666666); mPaint.setStyle(Style.STROKE); canvas.drawRect(buttonBounds, mPaint); mPaint.setStyle(Style.FILL); mPaint.setColor(0xFF000000); String name = selection.name; int heightAdj = getTextHeight(name, mPaint) / 2; canvas.drawText(name, buttonBounds.left + 0.5f * mColWidth, buttonBounds.top + 0.5f * mRowHeight + heightAdj, mPaint); } } } } mPaint.setColor(0xFF666666); if (mUI == UI.CHORD) { canvas.drawText(mThicknessName, bounds.left + mColWidth / 2, bounds.top + mRowHeight / 2 + getTextHeight(mThicknessName, mPaint) / 2 - 30, mPaint); canvas.drawText(mColorName, bounds.left + mColWidth / 2, bounds.top + mRowHeight / 2 + getTextHeight(mColorName, mPaint) / 2, mPaint); canvas.drawText(mToolName, bounds.left + mColWidth / 2, bounds.top + mRowHeight / 2 + getTextHeight(mToolName, mPaint) / 2 + 30, mPaint); } else if (mUI == UI.GESTURE) { String tools = mThicknessName + " " + mColorName + " " + mToolName; int padding = 10; mPaint.setColor(0xBBAAAAAA); canvas.drawRect(0, getHeight() - getTextHeight(tools, mPaint) - padding * 2, getTextWidth(tools, mPaint) + padding * 2, getHeight(), mPaint); mPaint.setColor(0xFF444444); canvas.drawText(tools, getTextWidth(tools, mPaint) / 2 + padding, getHeight() - padding, mPaint); } if (mShowGestureMenu) { PointF origin = mOrigins.get(mGestureFinger); if (isInCircle(mGestureFingerPos, origin.x, origin.y - mGestureButtonDist, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x; mActiveCategoryOrigin.y = origin.y - mGestureButtonDist; mActiveCategory = Gesture.UP; } else if (isInCircle(mGestureFingerPos, origin.x - mGestureButtonDist, origin.y, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x - mGestureButtonDist; mActiveCategoryOrigin.y = origin.y; mActiveCategory = Gesture.LEFT; } else if (isInCircle(mGestureFingerPos, origin.x + mGestureButtonDist, origin.y, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x + mGestureButtonDist; mActiveCategoryOrigin.y = origin.y; mActiveCategory = Gesture.RIGHT; } else if (isInCircle(mGestureFingerPos, origin.x, origin.y + mGestureButtonDist, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x; mActiveCategoryOrigin.y = origin.y + mGestureButtonDist; mActiveCategory = Gesture.DOWN; } boolean greyout = mActiveCategory != Gesture.UNKNOWN; mPaint.setTextSize(22); int size = mGestureButtonSize; drawGestureButton(canvas, "Tools", origin.x, origin.y - mGestureButtonDist, size, mPaint, mActiveCategory == Gesture.UP, greyout); drawGestureButton(canvas, "Colors", origin.x - mGestureButtonDist, origin.y, size, mPaint, mActiveCategory == Gesture.LEFT, greyout); drawGestureButton(canvas, "Colors", origin.x + mGestureButtonDist, origin.y, size, mPaint, mActiveCategory == Gesture.RIGHT, greyout); drawGestureButton(canvas, "Widths", origin.x, origin.y + mGestureButtonDist, size, mPaint, mActiveCategory == Gesture.DOWN, greyout); mPaint.setTextSize(18); int subSize = (int)(size * 0.70); int subDist = size + subSize; float subOriginX = mActiveCategoryOrigin.x; float subOriginY = mActiveCategoryOrigin.y; if (isInCircle(mGestureFingerPos, subOriginX, subOriginY - subDist, subSize)) { mSubSelection = Gesture.UP; } else if (isInCircle(mGestureFingerPos, subOriginX - subDist, subOriginY, subSize)) { mSubSelection = Gesture.LEFT; } else if (isInCircle(mGestureFingerPos, subOriginX + subDist, subOriginY, subSize)) { mSubSelection = Gesture.RIGHT; } else if (isInCircle(mGestureFingerPos, subOriginX, subOriginY + subDist, subSize)) { mSubSelection = Gesture.DOWN; } else { mSubSelection = Gesture.UNKNOWN; } switch (mActiveCategory) { case UP: drawGestureButton(canvas, "Paintbrush", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Rectangle", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "Line", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Circle", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; case LEFT: drawGestureButton(canvas, "Red", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Black", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "Green", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Blue", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; case RIGHT: drawGestureButton(canvas, "Magenta", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Cyan", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "White", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Yellow", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; case DOWN: drawGestureButton(canvas, "Thin", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Fine", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "Wide", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Normal", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; default: break; } mPaint.setTextSize(26); } } private boolean isInCircle(PointF point, float cx, float cy, float radius) { float dx = point.x - cx; float dy = point.y - cy; double distance = Math.sqrt(dx*dx + dy*dy); return distance < radius; } private void drawGestureButton(Canvas canvas, String text, float x, float y, int size, Paint paint, boolean highlight, boolean greyout) { paint.getTextBounds(text, 0, text.length(), mTextBounds); if (highlight) mPaint.setColor(0xFFAAAAAA); else if (greyout) mPaint.setColor(0xFFDDDDDD); else mPaint.setColor(0xFFCCCCCC); canvas.drawCircle(x, y, size, paint); if (greyout && !highlight) { mPaint.setColor(0xEE777777); } else { mPaint.setColor(0xEE000000); mPaint.setShadowLayer(2, 1, 1, 0x33000000); } canvas.drawText(text, x, y + mTextBounds.height() / 2, mPaint); mPaint.setShadowLayer(0, 0, 0, 0); } private int getTextHeight(String text, Paint paint) { mPaint.getTextBounds(text, 0, text.length(), mTextBounds); return mTextBounds.height(); } private int getTextWidth(String text, Paint paint) { mPaint.getTextBounds(text, 0, text.length(), mTextBounds); return mTextBounds.width(); } @Override public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); long now = System.nanoTime(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mLog.event("Touch down: " + id); mFingers.add(id); if (mUI == UI.CHORD) { if (event.getPointerCount() == 1) mCheckOverlay = true; if (getOverlayButtonBounds().contains(x, y)) { mFingerInside = id; mPressedInsideTime = now; mIgnoredFingers.add(mFingerInside); } else { int col = (int) (x / mColWidth); int row = (int) (y / mRowHeight); if (mLeftHanded) col = mCols - col - 1; mSelected = row * mCols + col; mRecentTouches.put(mSelected, now); } for (int i = 0; i < mRecentTouches.size(); i++) { int selection = mRecentTouches.keyAt(i); long time = mRecentTouches.valueAt(i); if ((now - time < mChordDelay && now - mPressedInsideTime < mChordDelay) || mShowOverlay) { changeSelection(selection); mCheckOverlay = false; mRecentTouches.removeAt(i); i--; } else if (now - time > mChordDelay) { mRecentTouches.removeAt(i); i--; } } } else if (mUI == UI.GESTURE) { if (event.getPointerCount() == 1) { mGestureDetector.clear(); mPossibleGestureFinger = id; mGestureFingerPos = new PointF(x, y); mPossibleGestureFingerTime = now; } else { mPossibleGestureFinger = -1; mGestureFinger = -1; mShowGestureMenu = false; + mActiveCategory = Gesture.UNKNOWN; } } if (!mShowOverlay) { mOrigins.put(id, new PointF(x, y)); mTool.touchStart(id, x, y); } break; case MotionEvent.ACTION_MOVE: if (mShowOverlay) break; int count = event.getPointerCount(); for (int i = 0; i < count; i++) { int fingerId = event.getPointerId(i); if (fingerId == mGestureFinger) { mGestureFingerPos = new PointF(x, y); mGestureDetector.addPoint(x, y); } if(mIgnoredFingers.contains(fingerId)) continue; float x2 = event.getX(i); float y2 = event.getY(i); PointF origin = mOrigins.get(fingerId); if (origin != null) { float dx = origin.x - x2; float dy = origin.y - y2; double dist = Math.sqrt(dx*dx + dy*dy); if (dist > mThreshold) { mOrigins.delete(fingerId); origin = null; } } if (origin == null) { mTool.touchMove(fingerId, x2, y2); if (!mChanged) { mChanged = true; mNextUndo = mBitmap.copy(mBitmap.getConfig(), true); } } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mLog.event("Touch up: " + id); mOrigins.delete(id); mFingers.remove(id); if (id == mFingerInside) mFingerInside = -1; if (id == mPossibleGestureFinger) mPossibleGestureFinger = -1; boolean draw = true; if (id == mGestureFinger) { mGestureFinger = -1; mShowGestureMenu = false; if (mActiveCategory != Gesture.UNKNOWN && mSubSelection != Gesture.UNKNOWN) { switch (mActiveCategory) { case UP: switch (mSubSelection) { case UP: mGesture = Gesture.UP; break; case LEFT: mGesture = Gesture.UP_LEFT; break; case RIGHT: mGesture = Gesture.UP_RIGHT; break; case DOWN: mGesture = Gesture.UP_DOWN; break; default: break; } break; case LEFT: switch (mSubSelection) { case UP: mGesture = Gesture.LEFT_UP; break; case LEFT: mGesture = Gesture.LEFT; break; case RIGHT: mGesture = Gesture.LEFT_RIGHT; break; case DOWN: mGesture = Gesture.LEFT_DOWN; break; default: break; } break; case RIGHT: switch (mSubSelection) { case UP: mGesture = Gesture.RIGHT_UP; break; case LEFT: mGesture = Gesture.RIGHT_LEFT; break; case RIGHT: mGesture = Gesture.RIGHT; break; case DOWN: mGesture = Gesture.RIGHT_DOWN; break; default: break; } break; case DOWN: switch (mSubSelection) { case UP: mGesture = Gesture.DOWN_UP; break; case LEFT: mGesture = Gesture.DOWN_LEFT; break; case RIGHT: mGesture = Gesture.DOWN_RIGHT; break; case DOWN: mGesture = Gesture.DOWN; break; default: break; } break; default: break; } } else { mGesture = mGestureDetector.recognize(); } if (mGestureSelections.containsKey(mGesture)) changeSelection(mGestureSelections.get(mGesture)); mActiveCategory = Gesture.UNKNOWN; draw = false; } if (mIgnoredFingers.contains(id)) { mIgnoredFingers.remove(id); draw = false; } if (mShowOverlay) { if (event.getPointerCount() == 1) { mShowOverlay = false; long duration = now - mOverlayStart; mLog.event("Overlay hidden after " + duration / 1000000 + " ms"); } } else if (draw) { if (event.getPointerCount() == 1 && mChanged) mUndo = mNextUndo; mTool.touchStop(id, x, y, new Canvas(mBitmap)); } if (event.getPointerCount() == 1) mChanged = false; break; } invalidate(); return true; } private void changeSelection(int selected) { changeSelection(selected, true); } private void changeSelection(int selected, boolean fromUser) { if (mTool != null) mTool.clearFingers(); for (int id : mFingers) { mIgnoredFingers.add(id); } mOrigins.clear(); Selection selection = mSelections[selected]; if (selection == null) return; if (fromUser) { synchronized (mFlashTimes) { mFlashTimes.put(selected, System.nanoTime()); } invalidate(); } switch (selection.type) { case TOOL: if (fromUser) mLog.event("Tool selected: " + selection.name); mTool = (Tool) selection.object; mToolName = selection.name; break; case COLOR: if (fromUser) mLog.event("Color selected: " + selection.name); mColor = (Integer) selection.object; mColorName = selection.name; break; case THICKNESS: if (fromUser) mLog.event("Thickness selected: " + selection.name); mThickness = (Integer) selection.object; mThicknessName = selection.name; break; case ACTION: if (fromUser) mLog.event("Action selected: " + selection.name); switch ((Action) selection.object) { case SAVE: break; case CLEAR: mUndo = mBitmap.copy(mBitmap.getConfig(), true); Canvas canvas = new Canvas(mBitmap); canvas.drawRGB(0xFF, 0xFF, 0xFF); break; case UNDO: if (mUndo != null) { Bitmap temp = mBitmap; mBitmap = mUndo; mUndo = temp; } break; } break; } if (fromUser && mStudyMode) { mStudyCtl.handleSelected(selection.name); mMainActivity.setTitle(mStudyCtl.getPrompt()); } } public void loadPreferences(SharedPreferences sharedPreferences) { mLeftHanded = sharedPreferences.getBoolean("pref_left_handed", false); mPermanentGrid = sharedPreferences.getBoolean("pref_permanent_grid", false); invalidate(); } }
true
true
public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); long now = System.nanoTime(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mLog.event("Touch down: " + id); mFingers.add(id); if (mUI == UI.CHORD) { if (event.getPointerCount() == 1) mCheckOverlay = true; if (getOverlayButtonBounds().contains(x, y)) { mFingerInside = id; mPressedInsideTime = now; mIgnoredFingers.add(mFingerInside); } else { int col = (int) (x / mColWidth); int row = (int) (y / mRowHeight); if (mLeftHanded) col = mCols - col - 1; mSelected = row * mCols + col; mRecentTouches.put(mSelected, now); } for (int i = 0; i < mRecentTouches.size(); i++) { int selection = mRecentTouches.keyAt(i); long time = mRecentTouches.valueAt(i); if ((now - time < mChordDelay && now - mPressedInsideTime < mChordDelay) || mShowOverlay) { changeSelection(selection); mCheckOverlay = false; mRecentTouches.removeAt(i); i--; } else if (now - time > mChordDelay) { mRecentTouches.removeAt(i); i--; } } } else if (mUI == UI.GESTURE) { if (event.getPointerCount() == 1) { mGestureDetector.clear(); mPossibleGestureFinger = id; mGestureFingerPos = new PointF(x, y); mPossibleGestureFingerTime = now; } else { mPossibleGestureFinger = -1; mGestureFinger = -1; mShowGestureMenu = false; } } if (!mShowOverlay) { mOrigins.put(id, new PointF(x, y)); mTool.touchStart(id, x, y); } break; case MotionEvent.ACTION_MOVE: if (mShowOverlay) break; int count = event.getPointerCount(); for (int i = 0; i < count; i++) { int fingerId = event.getPointerId(i); if (fingerId == mGestureFinger) { mGestureFingerPos = new PointF(x, y); mGestureDetector.addPoint(x, y); } if(mIgnoredFingers.contains(fingerId)) continue; float x2 = event.getX(i); float y2 = event.getY(i); PointF origin = mOrigins.get(fingerId); if (origin != null) { float dx = origin.x - x2; float dy = origin.y - y2; double dist = Math.sqrt(dx*dx + dy*dy); if (dist > mThreshold) { mOrigins.delete(fingerId); origin = null; } } if (origin == null) { mTool.touchMove(fingerId, x2, y2); if (!mChanged) { mChanged = true; mNextUndo = mBitmap.copy(mBitmap.getConfig(), true); } } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mLog.event("Touch up: " + id); mOrigins.delete(id); mFingers.remove(id); if (id == mFingerInside) mFingerInside = -1; if (id == mPossibleGestureFinger) mPossibleGestureFinger = -1; boolean draw = true; if (id == mGestureFinger) { mGestureFinger = -1; mShowGestureMenu = false; if (mActiveCategory != Gesture.UNKNOWN && mSubSelection != Gesture.UNKNOWN) { switch (mActiveCategory) { case UP: switch (mSubSelection) { case UP: mGesture = Gesture.UP; break; case LEFT: mGesture = Gesture.UP_LEFT; break; case RIGHT: mGesture = Gesture.UP_RIGHT; break; case DOWN: mGesture = Gesture.UP_DOWN; break; default: break; } break; case LEFT: switch (mSubSelection) { case UP: mGesture = Gesture.LEFT_UP; break; case LEFT: mGesture = Gesture.LEFT; break; case RIGHT: mGesture = Gesture.LEFT_RIGHT; break; case DOWN: mGesture = Gesture.LEFT_DOWN; break; default: break; } break; case RIGHT: switch (mSubSelection) { case UP: mGesture = Gesture.RIGHT_UP; break; case LEFT: mGesture = Gesture.RIGHT_LEFT; break; case RIGHT: mGesture = Gesture.RIGHT; break; case DOWN: mGesture = Gesture.RIGHT_DOWN; break; default: break; } break; case DOWN: switch (mSubSelection) { case UP: mGesture = Gesture.DOWN_UP; break; case LEFT: mGesture = Gesture.DOWN_LEFT; break; case RIGHT: mGesture = Gesture.DOWN_RIGHT; break; case DOWN: mGesture = Gesture.DOWN; break; default: break; } break; default: break; } } else { mGesture = mGestureDetector.recognize(); } if (mGestureSelections.containsKey(mGesture)) changeSelection(mGestureSelections.get(mGesture)); mActiveCategory = Gesture.UNKNOWN; draw = false; } if (mIgnoredFingers.contains(id)) { mIgnoredFingers.remove(id); draw = false; } if (mShowOverlay) { if (event.getPointerCount() == 1) { mShowOverlay = false; long duration = now - mOverlayStart; mLog.event("Overlay hidden after " + duration / 1000000 + " ms"); } } else if (draw) { if (event.getPointerCount() == 1 && mChanged) mUndo = mNextUndo; mTool.touchStop(id, x, y, new Canvas(mBitmap)); } if (event.getPointerCount() == 1) mChanged = false; break; } invalidate(); return true; }
public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); long now = System.nanoTime(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mLog.event("Touch down: " + id); mFingers.add(id); if (mUI == UI.CHORD) { if (event.getPointerCount() == 1) mCheckOverlay = true; if (getOverlayButtonBounds().contains(x, y)) { mFingerInside = id; mPressedInsideTime = now; mIgnoredFingers.add(mFingerInside); } else { int col = (int) (x / mColWidth); int row = (int) (y / mRowHeight); if (mLeftHanded) col = mCols - col - 1; mSelected = row * mCols + col; mRecentTouches.put(mSelected, now); } for (int i = 0; i < mRecentTouches.size(); i++) { int selection = mRecentTouches.keyAt(i); long time = mRecentTouches.valueAt(i); if ((now - time < mChordDelay && now - mPressedInsideTime < mChordDelay) || mShowOverlay) { changeSelection(selection); mCheckOverlay = false; mRecentTouches.removeAt(i); i--; } else if (now - time > mChordDelay) { mRecentTouches.removeAt(i); i--; } } } else if (mUI == UI.GESTURE) { if (event.getPointerCount() == 1) { mGestureDetector.clear(); mPossibleGestureFinger = id; mGestureFingerPos = new PointF(x, y); mPossibleGestureFingerTime = now; } else { mPossibleGestureFinger = -1; mGestureFinger = -1; mShowGestureMenu = false; mActiveCategory = Gesture.UNKNOWN; } } if (!mShowOverlay) { mOrigins.put(id, new PointF(x, y)); mTool.touchStart(id, x, y); } break; case MotionEvent.ACTION_MOVE: if (mShowOverlay) break; int count = event.getPointerCount(); for (int i = 0; i < count; i++) { int fingerId = event.getPointerId(i); if (fingerId == mGestureFinger) { mGestureFingerPos = new PointF(x, y); mGestureDetector.addPoint(x, y); } if(mIgnoredFingers.contains(fingerId)) continue; float x2 = event.getX(i); float y2 = event.getY(i); PointF origin = mOrigins.get(fingerId); if (origin != null) { float dx = origin.x - x2; float dy = origin.y - y2; double dist = Math.sqrt(dx*dx + dy*dy); if (dist > mThreshold) { mOrigins.delete(fingerId); origin = null; } } if (origin == null) { mTool.touchMove(fingerId, x2, y2); if (!mChanged) { mChanged = true; mNextUndo = mBitmap.copy(mBitmap.getConfig(), true); } } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mLog.event("Touch up: " + id); mOrigins.delete(id); mFingers.remove(id); if (id == mFingerInside) mFingerInside = -1; if (id == mPossibleGestureFinger) mPossibleGestureFinger = -1; boolean draw = true; if (id == mGestureFinger) { mGestureFinger = -1; mShowGestureMenu = false; if (mActiveCategory != Gesture.UNKNOWN && mSubSelection != Gesture.UNKNOWN) { switch (mActiveCategory) { case UP: switch (mSubSelection) { case UP: mGesture = Gesture.UP; break; case LEFT: mGesture = Gesture.UP_LEFT; break; case RIGHT: mGesture = Gesture.UP_RIGHT; break; case DOWN: mGesture = Gesture.UP_DOWN; break; default: break; } break; case LEFT: switch (mSubSelection) { case UP: mGesture = Gesture.LEFT_UP; break; case LEFT: mGesture = Gesture.LEFT; break; case RIGHT: mGesture = Gesture.LEFT_RIGHT; break; case DOWN: mGesture = Gesture.LEFT_DOWN; break; default: break; } break; case RIGHT: switch (mSubSelection) { case UP: mGesture = Gesture.RIGHT_UP; break; case LEFT: mGesture = Gesture.RIGHT_LEFT; break; case RIGHT: mGesture = Gesture.RIGHT; break; case DOWN: mGesture = Gesture.RIGHT_DOWN; break; default: break; } break; case DOWN: switch (mSubSelection) { case UP: mGesture = Gesture.DOWN_UP; break; case LEFT: mGesture = Gesture.DOWN_LEFT; break; case RIGHT: mGesture = Gesture.DOWN_RIGHT; break; case DOWN: mGesture = Gesture.DOWN; break; default: break; } break; default: break; } } else { mGesture = mGestureDetector.recognize(); } if (mGestureSelections.containsKey(mGesture)) changeSelection(mGestureSelections.get(mGesture)); mActiveCategory = Gesture.UNKNOWN; draw = false; } if (mIgnoredFingers.contains(id)) { mIgnoredFingers.remove(id); draw = false; } if (mShowOverlay) { if (event.getPointerCount() == 1) { mShowOverlay = false; long duration = now - mOverlayStart; mLog.event("Overlay hidden after " + duration / 1000000 + " ms"); } } else if (draw) { if (event.getPointerCount() == 1 && mChanged) mUndo = mNextUndo; mTool.touchStop(id, x, y, new Canvas(mBitmap)); } if (event.getPointerCount() == 1) mChanged = false; break; } invalidate(); return true; }
diff --git a/src/de/blau/android/views/overlay/OpenStreetMapTilesOverlay.java b/src/de/blau/android/views/overlay/OpenStreetMapTilesOverlay.java index 9fa6c3d..0ac7da6 100644 --- a/src/de/blau/android/views/overlay/OpenStreetMapTilesOverlay.java +++ b/src/de/blau/android/views/overlay/OpenStreetMapTilesOverlay.java @@ -1,206 +1,208 @@ package de.blau.android.views.overlay; import de.blau.android.services.util.OpenStreetMapTile; import de.blau.android.Map; import de.blau.android.views.IMapView; import de.blau.android.views.util.OpenStreetMapTileServer; import de.blau.android.views.util.OpenStreetMapTileProvider; import de.blau.android.util.GeoMath; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.os.Handler; import android.os.Message; import android.view.View; /** * Overlay that draws downloaded tiles which may be displayed on top of an * {@link IMapView}. To add an overlay, subclass this class, create an * instance, and add it to the list obtained from getOverlays() of * {@link Map}. * <br/> * This class was taken from OpenStreetMapViewer (original package org.andnav.osm) in 2010-06 * and changed significantly by Marcus Wolschon to be integrated into the de.blau.androin * OSMEditor. * @author Nicolas Gramlich * @author Marcus Wolschon <[email protected]> */ public class OpenStreetMapTilesOverlay extends OpenStreetMapViewOverlay { /** * The view we are a part of. */ protected View myView; /** * The tile-server to load a rendered map from. */ protected OpenStreetMapTileServer myRendererInfo; /** Current renderer */ protected final OpenStreetMapTileProvider mTileProvider; protected final Paint mPaint = new Paint(); /** * * @param aView The view we are a part of. * @param aRendererInfo The tile-server to load a rendered map from. * @param aTileProvider (may be null) */ public OpenStreetMapTilesOverlay(final View aView, final OpenStreetMapTileServer aRendererInfo, final OpenStreetMapTileProvider aTileProvider) { myView = aView; myRendererInfo = aRendererInfo; if(aTileProvider == null) { mTileProvider = new OpenStreetMapTileProvider(myView.getContext().getApplicationContext(), new SimpleInvalidationHandler()); } else { mTileProvider = aTileProvider; } } public void onDestroy() { mTileProvider.clear(); } public OpenStreetMapTileServer getRendererInfo() { return myRendererInfo; } public void setRendererInfo(final OpenStreetMapTileServer aRendererInfo) { myRendererInfo = aRendererInfo; } public void setAlpha(int a) { mPaint.setAlpha(a); } /** * @param x a x tile -number * @param aZoomLevel a zoom-level of a tile * @return the longitude of the tile */ static double tile2lon(int x, int aZoomLevel) { return x / Math.pow(2.0, aZoomLevel) * 360.0 - 180; } /** * @param y a y tile -number * @param aZoomLevel a zoom-level of a tile * @return the latitude of the tile */ static double tile2lat(int y, int aZoomLevel) { double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, aZoomLevel); return Math.toDegrees(Math.atan(Math.sinh(n))); } /** * {@inheritDoc}. */ @Override public void onDraw(Canvas c, IMapView osmv) { // Do some calculations and drag attributes to local variables to save //some performance. final Rect viewPort = c.getClipBounds(); final int zoomLevel = osmv.getZoomLevel(viewPort); final OpenStreetMapTile tile = new OpenStreetMapTile(0, 0, 0, 0); // reused instance of OpenStreetMapTile tile.rendererID = myRendererInfo.ordinal(); // TODO get from service double lonLeft = GeoMath.xToLonE7(c.getWidth() , osmv.getViewBox(), viewPort.left ) / 1E7d; double lonRight = GeoMath.xToLonE7(c.getWidth() , osmv.getViewBox(), viewPort.right ) / 1E7d; double latTop = GeoMath.yToLatE7(c.getHeight(), osmv.getViewBox(), viewPort.top ) / 1E7d; double latBottom = GeoMath.yToLatE7(c.getHeight(), osmv.getViewBox(), viewPort.bottom) / 1E7d; // pseudo-code for lon/lat to tile numbers //n = 2 ^ zoom //xtile = ((lon_deg + 180) / 360) * n //ytile = (1 - (log(tan(lat_rad) + sec(lat_rad)) / π)) / 2 * n int xTileLeft = (int) Math.floor(((lonLeft + 180d) / 360d) * Math.pow(2d, zoomLevel)); int xTileRight = (int) Math.floor(((lonRight + 180d) / 360d) * Math.pow(2d, zoomLevel)); int yTileTop = (int) Math.floor((1d - Math.log(Math.tan(Math.toRadians(latTop )) + 1d / Math.cos(Math.toRadians(latTop ))) / Math.PI) / 2d * Math.pow(2d, zoomLevel)); int yTileBottom = (int) Math.floor((1d - Math.log(Math.tan(Math.toRadians(latBottom)) + 1d / Math.cos(Math.toRadians(latBottom))) / Math.PI) / 2d * Math.pow(2d, zoomLevel)); final int tileNeededLeft = Math.min(xTileLeft, xTileRight); final int tileNeededRight = Math.max(xTileLeft, xTileRight); final int tileNeededTop = Math.min(yTileTop, yTileBottom); final int tileNeededBottom = Math.max(yTileTop, yTileBottom); final int mapTileMask = (1 << zoomLevel) - 1; // Draw all the MapTiles that intersect with the screen // y = y tile number (latitude) for (int y = tileNeededTop; y <= tileNeededBottom; y++) { // x = x tile number (longitude) for (int x = tileNeededLeft; x <= tileNeededRight; x++) { // Construct a URLString, which represents the MapTile tile.zoomLevel = zoomLevel; tile.y = y & mapTileMask; tile.x = x & mapTileMask; int sz = 256; int tx = 0; int ty = 0; while (!mTileProvider.isTileAvailable(tile) && tile.zoomLevel > 0) { mTileProvider.preCacheTile(tile); --tile.zoomLevel; - sz /= 2; - if ((tile.x & 1) != 0) tx += sz; - if ((tile.y & 1) != 0) ty += sz; + sz >>= 1; + tx >>= 1; + ty >>= 1; + if ((tile.x & 1) != 0) tx += 128; + if ((tile.y & 1) != 0) ty += 128; tile.x >>= 1; tile.y >>= 1; } if (mTileProvider.isTileAvailable(tile)) { c.drawBitmap( mTileProvider.getMapTile(tile), new Rect(tx, ty, tx + sz, ty + sz), getScreenRectForTile(c, osmv, zoomLevel, y, x), mPaint); } } } } /** * @param c the canvas we draw to (we need it´s clpi-bound´s width and height) * @param osmv the view with it´s viewBox * @param zoomLevel the zoom-level of the tile * @param y the y-number of the tile * @param x the x-number of the tile * @return the rectangle of screen-coordinates it consumes. */ private Rect getScreenRectForTile(Canvas c, IMapView osmv, final int zoomLevel, int y, int x) { double north = tile2lat(y, zoomLevel); double south = tile2lat(y + 1, zoomLevel); double west = tile2lon(x, zoomLevel); double east = tile2lon(x + 1, zoomLevel); int screenLeft = (int) Math.round(GeoMath.lonE7ToX(c.getClipBounds().width(), osmv.getViewBox(), (int) (west * 1E7))); int screenRight = (int) Math.round(GeoMath.lonE7ToX(c.getClipBounds().width(), osmv.getViewBox(), (int) (east * 1E7))); int screenTop = (int) Math.round(GeoMath.latE7ToY(c.getClipBounds().height(), osmv.getViewBox(), (int) (north * 1E7))); int screenBottom = (int) Math.round(GeoMath.latE7ToY(c.getClipBounds().height(), osmv.getViewBox(), (int) (south * 1E7))); return new Rect(screenLeft, screenTop, screenRight, screenBottom); } /** * {@inheritDoc}. */ @Override public void onDrawFinished(Canvas c, IMapView osmv) { } /** * Invalidate myView when a new tile got downloaded. */ private class SimpleInvalidationHandler extends Handler { @Override public void handleMessage(final Message msg) { switch (msg.what) { case OpenStreetMapTile.MAPTILE_SUCCESS_ID: myView.invalidate(); break; } } } }
true
true
public void onDraw(Canvas c, IMapView osmv) { // Do some calculations and drag attributes to local variables to save //some performance. final Rect viewPort = c.getClipBounds(); final int zoomLevel = osmv.getZoomLevel(viewPort); final OpenStreetMapTile tile = new OpenStreetMapTile(0, 0, 0, 0); // reused instance of OpenStreetMapTile tile.rendererID = myRendererInfo.ordinal(); // TODO get from service double lonLeft = GeoMath.xToLonE7(c.getWidth() , osmv.getViewBox(), viewPort.left ) / 1E7d; double lonRight = GeoMath.xToLonE7(c.getWidth() , osmv.getViewBox(), viewPort.right ) / 1E7d; double latTop = GeoMath.yToLatE7(c.getHeight(), osmv.getViewBox(), viewPort.top ) / 1E7d; double latBottom = GeoMath.yToLatE7(c.getHeight(), osmv.getViewBox(), viewPort.bottom) / 1E7d; // pseudo-code for lon/lat to tile numbers //n = 2 ^ zoom //xtile = ((lon_deg + 180) / 360) * n //ytile = (1 - (log(tan(lat_rad) + sec(lat_rad)) / π)) / 2 * n int xTileLeft = (int) Math.floor(((lonLeft + 180d) / 360d) * Math.pow(2d, zoomLevel)); int xTileRight = (int) Math.floor(((lonRight + 180d) / 360d) * Math.pow(2d, zoomLevel)); int yTileTop = (int) Math.floor((1d - Math.log(Math.tan(Math.toRadians(latTop )) + 1d / Math.cos(Math.toRadians(latTop ))) / Math.PI) / 2d * Math.pow(2d, zoomLevel)); int yTileBottom = (int) Math.floor((1d - Math.log(Math.tan(Math.toRadians(latBottom)) + 1d / Math.cos(Math.toRadians(latBottom))) / Math.PI) / 2d * Math.pow(2d, zoomLevel)); final int tileNeededLeft = Math.min(xTileLeft, xTileRight); final int tileNeededRight = Math.max(xTileLeft, xTileRight); final int tileNeededTop = Math.min(yTileTop, yTileBottom); final int tileNeededBottom = Math.max(yTileTop, yTileBottom); final int mapTileMask = (1 << zoomLevel) - 1; // Draw all the MapTiles that intersect with the screen // y = y tile number (latitude) for (int y = tileNeededTop; y <= tileNeededBottom; y++) { // x = x tile number (longitude) for (int x = tileNeededLeft; x <= tileNeededRight; x++) { // Construct a URLString, which represents the MapTile tile.zoomLevel = zoomLevel; tile.y = y & mapTileMask; tile.x = x & mapTileMask; int sz = 256; int tx = 0; int ty = 0; while (!mTileProvider.isTileAvailable(tile) && tile.zoomLevel > 0) { mTileProvider.preCacheTile(tile); --tile.zoomLevel; sz /= 2; if ((tile.x & 1) != 0) tx += sz; if ((tile.y & 1) != 0) ty += sz; tile.x >>= 1; tile.y >>= 1; } if (mTileProvider.isTileAvailable(tile)) { c.drawBitmap( mTileProvider.getMapTile(tile), new Rect(tx, ty, tx + sz, ty + sz), getScreenRectForTile(c, osmv, zoomLevel, y, x), mPaint); } } } }
public void onDraw(Canvas c, IMapView osmv) { // Do some calculations and drag attributes to local variables to save //some performance. final Rect viewPort = c.getClipBounds(); final int zoomLevel = osmv.getZoomLevel(viewPort); final OpenStreetMapTile tile = new OpenStreetMapTile(0, 0, 0, 0); // reused instance of OpenStreetMapTile tile.rendererID = myRendererInfo.ordinal(); // TODO get from service double lonLeft = GeoMath.xToLonE7(c.getWidth() , osmv.getViewBox(), viewPort.left ) / 1E7d; double lonRight = GeoMath.xToLonE7(c.getWidth() , osmv.getViewBox(), viewPort.right ) / 1E7d; double latTop = GeoMath.yToLatE7(c.getHeight(), osmv.getViewBox(), viewPort.top ) / 1E7d; double latBottom = GeoMath.yToLatE7(c.getHeight(), osmv.getViewBox(), viewPort.bottom) / 1E7d; // pseudo-code for lon/lat to tile numbers //n = 2 ^ zoom //xtile = ((lon_deg + 180) / 360) * n //ytile = (1 - (log(tan(lat_rad) + sec(lat_rad)) / π)) / 2 * n int xTileLeft = (int) Math.floor(((lonLeft + 180d) / 360d) * Math.pow(2d, zoomLevel)); int xTileRight = (int) Math.floor(((lonRight + 180d) / 360d) * Math.pow(2d, zoomLevel)); int yTileTop = (int) Math.floor((1d - Math.log(Math.tan(Math.toRadians(latTop )) + 1d / Math.cos(Math.toRadians(latTop ))) / Math.PI) / 2d * Math.pow(2d, zoomLevel)); int yTileBottom = (int) Math.floor((1d - Math.log(Math.tan(Math.toRadians(latBottom)) + 1d / Math.cos(Math.toRadians(latBottom))) / Math.PI) / 2d * Math.pow(2d, zoomLevel)); final int tileNeededLeft = Math.min(xTileLeft, xTileRight); final int tileNeededRight = Math.max(xTileLeft, xTileRight); final int tileNeededTop = Math.min(yTileTop, yTileBottom); final int tileNeededBottom = Math.max(yTileTop, yTileBottom); final int mapTileMask = (1 << zoomLevel) - 1; // Draw all the MapTiles that intersect with the screen // y = y tile number (latitude) for (int y = tileNeededTop; y <= tileNeededBottom; y++) { // x = x tile number (longitude) for (int x = tileNeededLeft; x <= tileNeededRight; x++) { // Construct a URLString, which represents the MapTile tile.zoomLevel = zoomLevel; tile.y = y & mapTileMask; tile.x = x & mapTileMask; int sz = 256; int tx = 0; int ty = 0; while (!mTileProvider.isTileAvailable(tile) && tile.zoomLevel > 0) { mTileProvider.preCacheTile(tile); --tile.zoomLevel; sz >>= 1; tx >>= 1; ty >>= 1; if ((tile.x & 1) != 0) tx += 128; if ((tile.y & 1) != 0) ty += 128; tile.x >>= 1; tile.y >>= 1; } if (mTileProvider.isTileAvailable(tile)) { c.drawBitmap( mTileProvider.getMapTile(tile), new Rect(tx, ty, tx + sz, ty + sz), getScreenRectForTile(c, osmv, zoomLevel, y, x), mPaint); } } } }
diff --git a/src/test/java/org/iplantc/de/client/GwtTestDataUtils.java b/src/test/java/org/iplantc/de/client/GwtTestDataUtils.java index dea5c776..b881c2fb 100644 --- a/src/test/java/org/iplantc/de/client/GwtTestDataUtils.java +++ b/src/test/java/org/iplantc/de/client/GwtTestDataUtils.java @@ -1,313 +1,316 @@ package org.iplantc.de.client; import java.util.ArrayList; import java.util.List; import org.iplantc.core.uidiskresource.client.models.DiskResource; import org.iplantc.core.uidiskresource.client.models.File; import org.iplantc.core.uidiskresource.client.models.Folder; import org.iplantc.core.uidiskresource.client.models.Permissions; import org.iplantc.core.uidiskresource.client.util.DiskResourceUtil; import org.iplantc.de.client.utils.DataUtils; import org.iplantc.de.client.utils.DataUtils.Action; import com.google.gwt.junit.client.GWTTestCase; public class GwtTestDataUtils extends GWTTestCase { @Override public String getModuleName() { return "org.iplantc.de.discoveryenvironment"; //$NON-NLS-1$ } private List<DiskResource> buildMixedPermissionsFilesList() { List<DiskResource> list = new ArrayList<DiskResource>(); File f1 = new File("/iplant/home/ipctest/analyses/1/test1", "test1", new Permissions(true, false, false)); File f2 = new File("/iplant/home/ipctest/analyses/1/test2", "test2", new Permissions(true, true, true)); File f3 = new File("/iplant/home/ipctest/analyses/1/test3", "test3", new Permissions(true, false, false)); list.add(f1); list.add(f2); list.add(f3); return list; } private List<DiskResource> buildReadOnlyFilesList() { List<DiskResource> list = new ArrayList<DiskResource>(); File f1 = new File("/iplant/home/ipctest/analyses/1/test1", "test1", new Permissions(true, false, false)); File f2 = new File("/iplant/home/ipctest/analyses/1/test2", "test2", new Permissions(true, false, false)); File f3 = new File("/iplant/home/ipctest/analyses/1/test3", "test3", new Permissions(true, false, false)); list.add(f1); list.add(f2); list.add(f3); return list; } private List<DiskResource> buildReadWriteFilesList() { List<DiskResource> list = new ArrayList<DiskResource>(); File f1 = new File("/iplant/home/ipctest/analyses/1/test1", "test1", new Permissions(true, true, true)); File f2 = new File("/iplant/home/ipctest/analyses/1/test2", "test2", new Permissions(true, true, true)); File f3 = new File("/iplant/home/ipctest/analyses/1/test3", "test3", new Permissions(true, true, true)); list.add(f1); list.add(f2); list.add(f3); return list; } private List<DiskResource> buildFileFolderList() { List<DiskResource> list = new ArrayList<DiskResource>(); File f1 = new File("/iplant/home/ipctest/analyses/1/test1", "test1", new Permissions(true, true, true)); File f2 = new File("/iplant/home/ipctest/analyses/1/test2", "test2", new Permissions(true, true, true)); File f3 = new File("/iplant/home/ipctest/analyses/1/test3", "test3", new Permissions(true, true, true)); Folder fo1 = new Folder("/iplant/home/ipctest/analyses/1", "1", false, new Permissions(true, true, true)); list.add(f1); list.add(f2); list.add(f3); list.add(fo1); return list; } private File buildFile() { return new File("/iplant/home/ipctest/analyses/1/test1", "test1", new Permissions(true, true, true)); } private Folder buildFolder() { return new Folder("/iplant/home/ipctest/analyses/1", "1", false, new Permissions(true, true, true)); } private Folder buildReadOnlyFolder() { return new Folder("/iplant/home/ipctest/analyses/1", "1", false, new Permissions(true, false, false)); } private List<DiskResource> buildSingleFileList() { List<DiskResource> list = new ArrayList<DiskResource>(); list.add(buildFile()); return list; } private List<DiskResource> buildSingleFolderList() { List<DiskResource> list = new ArrayList<DiskResource>(); list.add(buildFolder()); return list; } private List<DiskResource> buildReadOnlyFolderList() { List<DiskResource> list = new ArrayList<DiskResource>(); Folder fo1 = new Folder("/iplant/home/ipctest/analyses/1", "1", false, new Permissions(true, false, false)); Folder fo2 = new Folder("/iplant/home/ipctest/analyses/2", "2", false, new Permissions(true, false, false)); Folder fo3 = new Folder("/iplant/home/ipctest/analyses/3", "3", false, new Permissions(true, false, false)); list.add(fo1); list.add(fo2); list.add(fo3); return list; } private List<DiskResource> buildReadWriteFolderList() { List<DiskResource> list = new ArrayList<DiskResource>(); Folder fo1 = new Folder("/iplant/home/ipctest/analyses/1", "1", false, new Permissions(true, true, true)); Folder fo2 = new Folder("/iplant/home/ipctest/analyses/2", "2", false, new Permissions(true, true, true)); Folder fo3 = new Folder("/iplant/home/ipctest/analyses/3", "3", false, new Permissions(true, true, true)); list.add(fo1); list.add(fo2); list.add(fo3); return list; } public void testEmptyHasFolders() { List<DiskResource> list = null; assertFalse(DataUtils.hasFolders(list)); list = new ArrayList<DiskResource>(); assertFalse(DataUtils.hasFolders(list)); } public void testHadFolders() { assertFalse(DataUtils.hasFolders(buildReadOnlyFilesList())); assertTrue(DataUtils.hasFolders(buildFileFolderList())); } public void testEmptySupportedActions() { List<DiskResource> list = null; List<Action> actions = DataUtils.getSupportedActions(list, null); assertEquals(0, actions.size()); list = new ArrayList<DiskResource>(); actions = DataUtils.getSupportedActions(list, null); assertEquals(0, actions.size()); } public void testSupportedActions() { List<Action> actions = DataUtils.getSupportedActions(buildSingleFileList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.SimpleDownload)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.RenameFile)); assertTrue(actions.contains(Action.View)); assertTrue(actions.contains(Action.ViewTree)); assertTrue(actions.contains(Action.Metadata)); assertTrue(actions.contains(Action.Share)); + assertTrue(actions.contains(Action.DataLinks)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); - assertEquals(8, actions.size()); + assertEquals(9, actions.size()); actions = DataUtils.getSupportedActions(buildSingleFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.RenameFolder)); assertTrue(actions.contains(Action.Metadata)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(5, actions.size()); actions = DataUtils.getSupportedActions(buildFileFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.Share)); + assertTrue(actions.contains(Action.DataLinks)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); - assertEquals(3, actions.size()); + assertEquals(4, actions.size()); actions = DataUtils.getSupportedActions(buildMixedPermissionsFilesList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.SimpleDownload)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.View)); assertTrue(actions.contains(Action.Share)); + assertTrue(actions.contains(Action.DataLinks)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); - assertEquals(5, actions.size()); + assertEquals(6, actions.size()); actions = DataUtils.getSupportedActions(buildReadOnlyFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(3, actions.size()); } public void testParseParentEmpty() { String parent = DiskResourceUtil.parseParent(null); assertEquals("", parent); parent = DiskResourceUtil.parseParent(""); assertEquals("", parent); } public void testParseParent() { String parent = DiskResourceUtil.parseParent("/iplant/home/ipctest/analyses/1"); assertEquals("/iplant/home/ipctest/analyses", parent); } public void testParseNameEmpty() { String name = DiskResourceUtil.parseNameFromPath(null); assertEquals("", name); name = DiskResourceUtil.parseNameFromPath(""); assertEquals("", name); } public void testParseName() { String name = DiskResourceUtil.parseNameFromPath("/iplant/home/ipctest/analyses/1"); assertEquals("1", name); name = DiskResourceUtil.parseNameFromPath("/iplant/home/ipctest/analyses/space name"); assertEquals("space name", name); } public void testSizeForDisplay() { String size = DataUtils.getSizeForDisplay(512); assertEquals("512 bytes", size); size = DataUtils.getSizeForDisplay(1024); assertEquals("1.0 KB", size); size = DataUtils.getSizeForDisplay(1048576); assertEquals("1.0 MB", size); size = DataUtils.getSizeForDisplay(1073741824); assertEquals("1.0 GB", size); } public void testIsMovable() { assertFalse(DataUtils.isMovable(null)); assertFalse(DataUtils.isMovable(new ArrayList<DiskResource>())); assertTrue(DataUtils.isMovable(buildReadWriteFilesList())); assertTrue(DataUtils.isMovable(buildReadWriteFolderList())); assertFalse(DataUtils.isMovable(buildMixedPermissionsFilesList())); } public void testIsViewable() { assertFalse(DataUtils.isViewable(null)); assertFalse(DataUtils.isViewable(new ArrayList<DiskResource>())); assertTrue(DataUtils.isViewable(buildReadWriteFilesList())); assertTrue(DataUtils.isViewable(buildReadWriteFolderList())); assertTrue(DataUtils.isViewable(buildMixedPermissionsFilesList())); } public void testIsDownloadable() { assertFalse(DataUtils.isViewable(null)); assertFalse(DataUtils.isViewable(new ArrayList<DiskResource>())); assertTrue(DataUtils.isViewable(buildReadWriteFilesList())); assertTrue(DataUtils.isViewable(buildReadWriteFolderList())); assertTrue(DataUtils.isViewable(buildMixedPermissionsFilesList())); } public void testIsDeletable() { assertFalse(DataUtils.isDeletable(null)); assertFalse(DataUtils.isDeletable(new ArrayList<DiskResource>())); assertTrue(DataUtils.isDeletable(buildReadWriteFilesList())); assertTrue(DataUtils.isDeletable(buildReadWriteFolderList())); assertFalse(DataUtils.isDeletable(buildMixedPermissionsFilesList())); assertFalse(DataUtils.isDeletable(buildReadOnlyFolderList())); } public void testIsRenamable() { assertFalse(DataUtils.isRenamable(null)); assertTrue(DataUtils.isRenamable(buildFolder())); assertTrue(DataUtils.isRenamable(buildFile())); } public void testCanUploadFolder() { assertFalse(DataUtils.canUploadToThisFolder(buildReadOnlyFolder())); assertTrue(DataUtils.canUploadToThisFolder(buildFolder())); } public void testcanCreateFolderInThisFolder() { assertFalse(DataUtils.canCreateFolderInThisFolder(buildReadOnlyFolder())); assertTrue(DataUtils.canCreateFolderInThisFolder(buildFolder())); } }
false
true
public void testSupportedActions() { List<Action> actions = DataUtils.getSupportedActions(buildSingleFileList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.SimpleDownload)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.RenameFile)); assertTrue(actions.contains(Action.View)); assertTrue(actions.contains(Action.ViewTree)); assertTrue(actions.contains(Action.Metadata)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(8, actions.size()); actions = DataUtils.getSupportedActions(buildSingleFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.RenameFolder)); assertTrue(actions.contains(Action.Metadata)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(5, actions.size()); actions = DataUtils.getSupportedActions(buildFileFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(3, actions.size()); actions = DataUtils.getSupportedActions(buildMixedPermissionsFilesList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.SimpleDownload)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.View)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(5, actions.size()); actions = DataUtils.getSupportedActions(buildReadOnlyFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(3, actions.size()); }
public void testSupportedActions() { List<Action> actions = DataUtils.getSupportedActions(buildSingleFileList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.SimpleDownload)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.RenameFile)); assertTrue(actions.contains(Action.View)); assertTrue(actions.contains(Action.ViewTree)); assertTrue(actions.contains(Action.Metadata)); assertTrue(actions.contains(Action.Share)); assertTrue(actions.contains(Action.DataLinks)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(9, actions.size()); actions = DataUtils.getSupportedActions(buildSingleFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.RenameFolder)); assertTrue(actions.contains(Action.Metadata)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(5, actions.size()); actions = DataUtils.getSupportedActions(buildFileFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.Share)); assertTrue(actions.contains(Action.DataLinks)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(4, actions.size()); actions = DataUtils.getSupportedActions(buildMixedPermissionsFilesList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.SimpleDownload)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.View)); assertTrue(actions.contains(Action.Share)); assertTrue(actions.contains(Action.DataLinks)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(6, actions.size()); actions = DataUtils.getSupportedActions(buildReadOnlyFolderList(), null); assertTrue(actions.contains(Action.Delete)); assertTrue(actions.contains(Action.BulkDownload)); assertTrue(actions.contains(Action.Share)); // assertTrue(actions.contains(Action.Copy)); // assertTrue(actions.contains(Action.Paste)); assertEquals(3, actions.size()); }
diff --git a/domain/src/main/java/org/fao/geonet/repository/GeonetRepositoryImpl.java b/domain/src/main/java/org/fao/geonet/repository/GeonetRepositoryImpl.java index 6d50a068e1..cd3b24ab6b 100644 --- a/domain/src/main/java/org/fao/geonet/repository/GeonetRepositoryImpl.java +++ b/domain/src/main/java/org/fao/geonet/repository/GeonetRepositoryImpl.java @@ -1,45 +1,45 @@ package org.fao.geonet.repository; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import java.io.Serializable; /** * Abstract super class of Geonetwork repositories that contains extra useful implementations. * * @param <T> The entity type * @param <ID> The entity id type * <p/> * User: jeichar * Date: 9/5/13 * Time: 11:26 AM */ public class GeonetRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements GeonetRepository<T, ID> { protected EntityManager _entityManager; private final Class<T> _entityClass; protected GeonetRepositoryImpl(Class<T> domainClass, EntityManager entityManager) { super(domainClass, entityManager); this._entityManager = entityManager; this._entityClass = domainClass; } - public T update(int id, Updater<T> updater) { + public T update(ID id, Updater<T> updater) { final T entity = _entityManager.find(this._entityClass, id); if (entity == null) { throw new EntityNotFoundException("No entity found with id: " + id); } updater.apply(entity); _entityManager.persist(entity); return entity; } }
true
true
public T update(int id, Updater<T> updater) { final T entity = _entityManager.find(this._entityClass, id); if (entity == null) { throw new EntityNotFoundException("No entity found with id: " + id); } updater.apply(entity); _entityManager.persist(entity); return entity; }
public T update(ID id, Updater<T> updater) { final T entity = _entityManager.find(this._entityClass, id); if (entity == null) { throw new EntityNotFoundException("No entity found with id: " + id); } updater.apply(entity); _entityManager.persist(entity); return entity; }
diff --git a/json-mapper/src/test/java/org/jongo/json/JsonEngine.java b/json-mapper/src/test/java/org/jongo/json/JsonEngine.java index 3e2e650..8d62ca2 100644 --- a/json-mapper/src/test/java/org/jongo/json/JsonEngine.java +++ b/json-mapper/src/test/java/org/jongo/json/JsonEngine.java @@ -1,64 +1,64 @@ /* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jongo.json; import com.mongodb.DBObject; import com.mongodb.util.JSON; import org.jongo.bson.Bson; import org.jongo.bson.BsonDocument; import org.jongo.marshall.Marshaller; import org.jongo.marshall.MarshallingException; import org.jongo.marshall.Unmarshaller; import org.jongo.marshall.jackson.configuration.Mapping; import java.io.StringWriter; import java.io.Writer; class JsonEngine implements Unmarshaller, Marshaller { private final Mapping config; public JsonEngine(Mapping config) { this.config = config; } public <T> T unmarshall(BsonDocument document, Class<T> clazz) throws MarshallingException { String json = document.toDBObject().toString(); try { return (T) config.getReader(clazz).readValue(json); } catch (Exception e) { String message = String.format("Unable to unmarshall from json: %s to %s", json, clazz); throw new MarshallingException(message, e); } } public BsonDocument marshall(Object pojo) throws MarshallingException { try { Writer writer = new StringWriter(); - config.getWriter(pojo.getClass()).writeValue(writer, pojo); + config.getWriter(pojo).writeValue(writer, pojo); DBObject dbObject = createDBObjectWithDriver(writer.toString()); return Bson.createDocument(dbObject); } catch (Exception e) { String message = String.format("Unable to marshall json from: %s", pojo); throw new MarshallingException(message, e); } } protected DBObject createDBObjectWithDriver(String json) { return (DBObject) JSON.parse(json); } }
true
true
public BsonDocument marshall(Object pojo) throws MarshallingException { try { Writer writer = new StringWriter(); config.getWriter(pojo.getClass()).writeValue(writer, pojo); DBObject dbObject = createDBObjectWithDriver(writer.toString()); return Bson.createDocument(dbObject); } catch (Exception e) { String message = String.format("Unable to marshall json from: %s", pojo); throw new MarshallingException(message, e); } }
public BsonDocument marshall(Object pojo) throws MarshallingException { try { Writer writer = new StringWriter(); config.getWriter(pojo).writeValue(writer, pojo); DBObject dbObject = createDBObjectWithDriver(writer.toString()); return Bson.createDocument(dbObject); } catch (Exception e) { String message = String.format("Unable to marshall json from: %s", pojo); throw new MarshallingException(message, e); } }
diff --git a/src/iitb/CRF/SegmentTrainer.java b/src/iitb/CRF/SegmentTrainer.java index bb83c12..263f657 100644 --- a/src/iitb/CRF/SegmentTrainer.java +++ b/src/iitb/CRF/SegmentTrainer.java @@ -1,191 +1,194 @@ package iitb.CRF; import java.lang.*; import java.io.*; import java.util.*; import cern.colt.matrix.*; import cern.colt.matrix.impl.*; /** * * @author Sunita Sarawagi * */ class SegmentTrainer extends SparseTrainer { public SegmentTrainer(CrfParams p) { super(p); logTrainer = true; } DoubleMatrix1D alpha_Y_Array[]; protected double computeFunctionGradient(double lambda[], double grad[]) { try { FeatureGeneratorNested featureGenNested = (FeatureGeneratorNested)featureGenerator; double logli = 0; for (int f = 0; f < lambda.length; f++) { grad[f] = -1*lambda[f]*params.invSigmaSquare; logli -= ((lambda[f]*lambda[f])*params.invSigmaSquare)/2; } diter.startScan(); int numRecord; for (numRecord = 0; diter.hasNext(); numRecord++) { CandSegDataSequence dataSeq = (CandSegDataSequence)diter.next(); if (params.debugLvl > 1) Util.printDbg("Read next seq: " + numRecord + " logli " + logli); for (int f = 0; f < lambda.length; f++) ExpF[f] = RobustMath.LOG0; int base = -1; if ((alpha_Y_Array == null) || (alpha_Y_Array.length < dataSeq.length()-base)) { alpha_Y_Array = new DoubleMatrix1D[2*dataSeq.length()]; for (int i = 0; i < alpha_Y_Array.length; i++) alpha_Y_Array[i] = new LogSparseDoubleMatrix1D(numY); } if ((beta_Y == null) || (beta_Y.length < dataSeq.length())) { beta_Y = new DoubleMatrix1D[2*dataSeq.length()]; for (int i = 0; i < beta_Y.length; i++) beta_Y[i] = new LogSparseDoubleMatrix1D(numY); } // compute beta values in a backward scan. // also scale beta-values as much as possible to avoid numerical overflows beta_Y[dataSeq.length()-1].assign(0); for (int i = dataSeq.length()-2; i >= 0; i--) { beta_Y[i].assign(RobustMath.LOG0); } CandidateSegments candidateSegs = (CandidateSegments)dataSeq; for (int segEnd = dataSeq.length()-1; segEnd >= 0; segEnd--) { for (int nc = candidateSegs.numCandSegmentsEndingAt(segEnd)-1; nc >= 0; nc--) { int segStart = candidateSegs.candSegmentStart(segEnd,nc); int ell = segEnd-segStart+1; int i = segStart-1; if (i < 0) continue; // compute the Mi matrix computeLogMi(dataSeq,i,i+ell,featureGenNested,lambda,Mi_YY,Ri_Y); tmp_Y.assign(beta_Y[i+ell]); tmp_Y.assign(Ri_Y,sumFunc); Mi_YY.zMult(tmp_Y, beta_Y[i],1,1,false); } } double thisSeqLogli = 0; boolean noneFired=true; alpha_Y_Array[0].assign(0); for (int i = 0; i < dataSeq.length(); i++) { alpha_Y_Array[i-base].assign(RobustMath.LOG0); for (int nc = candidateSegs.numCandSegmentsEndingAt(i)-1; nc >= 0; nc--) { int ell = i - candidateSegs.candSegmentStart(i,nc)+1; // compute the Mi matrix computeLogMi(dataSeq,i-ell,i,featureGenNested,lambda,Mi_YY,Ri_Y); boolean mAdded = false, rAdded = false; if (i-ell >= 0) { Mi_YY.zMult(alpha_Y_Array[i-ell-base],newAlpha_Y,1,0,true); newAlpha_Y.assign(Ri_Y,sumFunc); } else newAlpha_Y.assign(Ri_Y); alpha_Y_Array[i-base].assign(newAlpha_Y, RobustMath.logSumExpFunc); // find features that fire at this position.. featureGenNested.startScanFeaturesAt(dataSeq, i-ell,i); while (featureGenNested.hasNext()) { Feature feature = featureGenNested.next(); int f = feature.index(); int yp = feature.y(); int yprev = feature.yprev(); float val = feature.value(); if (dataSeq.holdsInTrainingData(feature,i-ell,i)) { grad[f] += val; thisSeqLogli += val*lambda[f]; noneFired=false; /* double lZx = alpha_Y_Array[i-base].zSum(); if ((thisSeqLogli > lZx) || (numRecord == 3)) { System.out.println("This is shady: something is wrong Pr(y|x) > 1!"); System.out.println("Sequence likelihood " + thisSeqLogli + " " + lZx + " " + Math.exp(lZx)); System.out.println("This Alpha-i " + alpha_Y_Array[i-base].toString()); } */ } if (yprev < 0) { ExpF[f] = RobustMath.logSumExp(ExpF[f], (newAlpha_Y.get(yp)+Math.log(val)+beta_Y[i].get(yp))); } else { ExpF[f] = RobustMath.logSumExp(ExpF[f], (alpha_Y_Array[i-ell-base].get(yprev)+Ri_Y.get(yp)+Mi_YY.get(yprev,yp)+Math.log(val)+beta_Y[i].get(yp))); } if (params.debugLvl > 3) { System.out.println(f + " " + feature + " " + dataSeq.holdsInTrainingData(feature,i-ell,i)); } } } if (params.debugLvl > 2) { System.out.println("Alpha-i " + alpha_Y_Array[i-base].toString()); System.out.println("Ri " + Ri_Y.toString()); System.out.println("Mi " + Mi_YY.toString()); System.out.println("Beta-i " + beta_Y[i].toString()); } } double lZx = alpha_Y_Array[dataSeq.length()-1-base].zSum(); thisSeqLogli -= lZx; logli += thisSeqLogli; // update grad. for (int f = 0; f < grad.length; f++) grad[f] -= Math.exp(ExpF[f]-lZx); - if ((thisSeqLogli > 0) || noneFired) { - System.out.println("This is shady: something is wrong Pr(y|x) > 1!"); + if (noneFired) { + System.out.println("WARNING: no features fired in the training set"); + } + if (thisSeqLogli > 0) { + System.out.println("ERROR: something is wrong Pr(y|x) > 1!"); } if (params.debugLvl > 1 || (thisSeqLogli > 0)) { System.out.println("Sequence likelihood " + thisSeqLogli + " " + lZx + " " + Math.exp(lZx)); System.out.println("Last Alpha-i " + alpha_Y_Array[dataSeq.length()-1-base].toString()); } } if (params.debugLvl > 2) { for (int f = 0; f < lambda.length; f++) System.out.print(lambda[f] + " "); System.out.println(" :x"); for (int f = 0; f < lambda.length; f++) System.out.print(grad[f] + " "); System.out.println(" :g"); } if (params.debugLvl > 0) { if (icall == 0) { Util.printDbg("Number of training records " + numRecord); } Util.printDbg("Iter " + icall + " loglikelihood "+logli + " gnorm " + norm(grad) + " xnorm "+ norm(lambda)); } return logli; } catch (Exception e) { e.printStackTrace(); System.exit(0); } return 0; } static void computeLogMi(CandSegDataSequence dataSeq, int prevPos, int pos, FeatureGeneratorNested featureGenNested, double[] lambda, DoubleMatrix2D Mi, DoubleMatrix1D Ri) { featureGenNested.startScanFeaturesAt(dataSeq,prevPos,pos); Iterator constraints = dataSeq.constraints(prevPos,pos); double defaultValue = 0; Mi.assign(defaultValue); Ri.assign(defaultValue); if (constraints != null) { for (; constraints.hasNext();) { Constraint constraint = (Constraint)constraints.next(); if (constraint.type() == Constraint.ALLOW_ONLY) { defaultValue = RobustMath.LOG0; Mi.assign(defaultValue); Ri.assign(defaultValue); RestrictConstraint cons = (RestrictConstraint)constraint; for (int c = cons.numAllowed()-1; c >= 0; c--) { Ri.set(cons.allowed(c),0); } } } } SparseTrainer.computeLogMiInitDone(featureGenNested,lambda,Mi,Ri,defaultValue); } };
true
true
protected double computeFunctionGradient(double lambda[], double grad[]) { try { FeatureGeneratorNested featureGenNested = (FeatureGeneratorNested)featureGenerator; double logli = 0; for (int f = 0; f < lambda.length; f++) { grad[f] = -1*lambda[f]*params.invSigmaSquare; logli -= ((lambda[f]*lambda[f])*params.invSigmaSquare)/2; } diter.startScan(); int numRecord; for (numRecord = 0; diter.hasNext(); numRecord++) { CandSegDataSequence dataSeq = (CandSegDataSequence)diter.next(); if (params.debugLvl > 1) Util.printDbg("Read next seq: " + numRecord + " logli " + logli); for (int f = 0; f < lambda.length; f++) ExpF[f] = RobustMath.LOG0; int base = -1; if ((alpha_Y_Array == null) || (alpha_Y_Array.length < dataSeq.length()-base)) { alpha_Y_Array = new DoubleMatrix1D[2*dataSeq.length()]; for (int i = 0; i < alpha_Y_Array.length; i++) alpha_Y_Array[i] = new LogSparseDoubleMatrix1D(numY); } if ((beta_Y == null) || (beta_Y.length < dataSeq.length())) { beta_Y = new DoubleMatrix1D[2*dataSeq.length()]; for (int i = 0; i < beta_Y.length; i++) beta_Y[i] = new LogSparseDoubleMatrix1D(numY); } // compute beta values in a backward scan. // also scale beta-values as much as possible to avoid numerical overflows beta_Y[dataSeq.length()-1].assign(0); for (int i = dataSeq.length()-2; i >= 0; i--) { beta_Y[i].assign(RobustMath.LOG0); } CandidateSegments candidateSegs = (CandidateSegments)dataSeq; for (int segEnd = dataSeq.length()-1; segEnd >= 0; segEnd--) { for (int nc = candidateSegs.numCandSegmentsEndingAt(segEnd)-1; nc >= 0; nc--) { int segStart = candidateSegs.candSegmentStart(segEnd,nc); int ell = segEnd-segStart+1; int i = segStart-1; if (i < 0) continue; // compute the Mi matrix computeLogMi(dataSeq,i,i+ell,featureGenNested,lambda,Mi_YY,Ri_Y); tmp_Y.assign(beta_Y[i+ell]); tmp_Y.assign(Ri_Y,sumFunc); Mi_YY.zMult(tmp_Y, beta_Y[i],1,1,false); } } double thisSeqLogli = 0; boolean noneFired=true; alpha_Y_Array[0].assign(0); for (int i = 0; i < dataSeq.length(); i++) { alpha_Y_Array[i-base].assign(RobustMath.LOG0); for (int nc = candidateSegs.numCandSegmentsEndingAt(i)-1; nc >= 0; nc--) { int ell = i - candidateSegs.candSegmentStart(i,nc)+1; // compute the Mi matrix computeLogMi(dataSeq,i-ell,i,featureGenNested,lambda,Mi_YY,Ri_Y); boolean mAdded = false, rAdded = false; if (i-ell >= 0) { Mi_YY.zMult(alpha_Y_Array[i-ell-base],newAlpha_Y,1,0,true); newAlpha_Y.assign(Ri_Y,sumFunc); } else newAlpha_Y.assign(Ri_Y); alpha_Y_Array[i-base].assign(newAlpha_Y, RobustMath.logSumExpFunc); // find features that fire at this position.. featureGenNested.startScanFeaturesAt(dataSeq, i-ell,i); while (featureGenNested.hasNext()) { Feature feature = featureGenNested.next(); int f = feature.index(); int yp = feature.y(); int yprev = feature.yprev(); float val = feature.value(); if (dataSeq.holdsInTrainingData(feature,i-ell,i)) { grad[f] += val; thisSeqLogli += val*lambda[f]; noneFired=false; /* double lZx = alpha_Y_Array[i-base].zSum(); if ((thisSeqLogli > lZx) || (numRecord == 3)) { System.out.println("This is shady: something is wrong Pr(y|x) > 1!"); System.out.println("Sequence likelihood " + thisSeqLogli + " " + lZx + " " + Math.exp(lZx)); System.out.println("This Alpha-i " + alpha_Y_Array[i-base].toString()); } */ } if (yprev < 0) { ExpF[f] = RobustMath.logSumExp(ExpF[f], (newAlpha_Y.get(yp)+Math.log(val)+beta_Y[i].get(yp))); } else { ExpF[f] = RobustMath.logSumExp(ExpF[f], (alpha_Y_Array[i-ell-base].get(yprev)+Ri_Y.get(yp)+Mi_YY.get(yprev,yp)+Math.log(val)+beta_Y[i].get(yp))); } if (params.debugLvl > 3) { System.out.println(f + " " + feature + " " + dataSeq.holdsInTrainingData(feature,i-ell,i)); } } } if (params.debugLvl > 2) { System.out.println("Alpha-i " + alpha_Y_Array[i-base].toString()); System.out.println("Ri " + Ri_Y.toString()); System.out.println("Mi " + Mi_YY.toString()); System.out.println("Beta-i " + beta_Y[i].toString()); } } double lZx = alpha_Y_Array[dataSeq.length()-1-base].zSum(); thisSeqLogli -= lZx; logli += thisSeqLogli; // update grad. for (int f = 0; f < grad.length; f++) grad[f] -= Math.exp(ExpF[f]-lZx); if ((thisSeqLogli > 0) || noneFired) { System.out.println("This is shady: something is wrong Pr(y|x) > 1!"); } if (params.debugLvl > 1 || (thisSeqLogli > 0)) { System.out.println("Sequence likelihood " + thisSeqLogli + " " + lZx + " " + Math.exp(lZx)); System.out.println("Last Alpha-i " + alpha_Y_Array[dataSeq.length()-1-base].toString()); } } if (params.debugLvl > 2) { for (int f = 0; f < lambda.length; f++) System.out.print(lambda[f] + " "); System.out.println(" :x"); for (int f = 0; f < lambda.length; f++) System.out.print(grad[f] + " "); System.out.println(" :g"); } if (params.debugLvl > 0) { if (icall == 0) { Util.printDbg("Number of training records " + numRecord); } Util.printDbg("Iter " + icall + " loglikelihood "+logli + " gnorm " + norm(grad) + " xnorm "+ norm(lambda)); } return logli; } catch (Exception e) { e.printStackTrace(); System.exit(0); } return 0; }
protected double computeFunctionGradient(double lambda[], double grad[]) { try { FeatureGeneratorNested featureGenNested = (FeatureGeneratorNested)featureGenerator; double logli = 0; for (int f = 0; f < lambda.length; f++) { grad[f] = -1*lambda[f]*params.invSigmaSquare; logli -= ((lambda[f]*lambda[f])*params.invSigmaSquare)/2; } diter.startScan(); int numRecord; for (numRecord = 0; diter.hasNext(); numRecord++) { CandSegDataSequence dataSeq = (CandSegDataSequence)diter.next(); if (params.debugLvl > 1) Util.printDbg("Read next seq: " + numRecord + " logli " + logli); for (int f = 0; f < lambda.length; f++) ExpF[f] = RobustMath.LOG0; int base = -1; if ((alpha_Y_Array == null) || (alpha_Y_Array.length < dataSeq.length()-base)) { alpha_Y_Array = new DoubleMatrix1D[2*dataSeq.length()]; for (int i = 0; i < alpha_Y_Array.length; i++) alpha_Y_Array[i] = new LogSparseDoubleMatrix1D(numY); } if ((beta_Y == null) || (beta_Y.length < dataSeq.length())) { beta_Y = new DoubleMatrix1D[2*dataSeq.length()]; for (int i = 0; i < beta_Y.length; i++) beta_Y[i] = new LogSparseDoubleMatrix1D(numY); } // compute beta values in a backward scan. // also scale beta-values as much as possible to avoid numerical overflows beta_Y[dataSeq.length()-1].assign(0); for (int i = dataSeq.length()-2; i >= 0; i--) { beta_Y[i].assign(RobustMath.LOG0); } CandidateSegments candidateSegs = (CandidateSegments)dataSeq; for (int segEnd = dataSeq.length()-1; segEnd >= 0; segEnd--) { for (int nc = candidateSegs.numCandSegmentsEndingAt(segEnd)-1; nc >= 0; nc--) { int segStart = candidateSegs.candSegmentStart(segEnd,nc); int ell = segEnd-segStart+1; int i = segStart-1; if (i < 0) continue; // compute the Mi matrix computeLogMi(dataSeq,i,i+ell,featureGenNested,lambda,Mi_YY,Ri_Y); tmp_Y.assign(beta_Y[i+ell]); tmp_Y.assign(Ri_Y,sumFunc); Mi_YY.zMult(tmp_Y, beta_Y[i],1,1,false); } } double thisSeqLogli = 0; boolean noneFired=true; alpha_Y_Array[0].assign(0); for (int i = 0; i < dataSeq.length(); i++) { alpha_Y_Array[i-base].assign(RobustMath.LOG0); for (int nc = candidateSegs.numCandSegmentsEndingAt(i)-1; nc >= 0; nc--) { int ell = i - candidateSegs.candSegmentStart(i,nc)+1; // compute the Mi matrix computeLogMi(dataSeq,i-ell,i,featureGenNested,lambda,Mi_YY,Ri_Y); boolean mAdded = false, rAdded = false; if (i-ell >= 0) { Mi_YY.zMult(alpha_Y_Array[i-ell-base],newAlpha_Y,1,0,true); newAlpha_Y.assign(Ri_Y,sumFunc); } else newAlpha_Y.assign(Ri_Y); alpha_Y_Array[i-base].assign(newAlpha_Y, RobustMath.logSumExpFunc); // find features that fire at this position.. featureGenNested.startScanFeaturesAt(dataSeq, i-ell,i); while (featureGenNested.hasNext()) { Feature feature = featureGenNested.next(); int f = feature.index(); int yp = feature.y(); int yprev = feature.yprev(); float val = feature.value(); if (dataSeq.holdsInTrainingData(feature,i-ell,i)) { grad[f] += val; thisSeqLogli += val*lambda[f]; noneFired=false; /* double lZx = alpha_Y_Array[i-base].zSum(); if ((thisSeqLogli > lZx) || (numRecord == 3)) { System.out.println("This is shady: something is wrong Pr(y|x) > 1!"); System.out.println("Sequence likelihood " + thisSeqLogli + " " + lZx + " " + Math.exp(lZx)); System.out.println("This Alpha-i " + alpha_Y_Array[i-base].toString()); } */ } if (yprev < 0) { ExpF[f] = RobustMath.logSumExp(ExpF[f], (newAlpha_Y.get(yp)+Math.log(val)+beta_Y[i].get(yp))); } else { ExpF[f] = RobustMath.logSumExp(ExpF[f], (alpha_Y_Array[i-ell-base].get(yprev)+Ri_Y.get(yp)+Mi_YY.get(yprev,yp)+Math.log(val)+beta_Y[i].get(yp))); } if (params.debugLvl > 3) { System.out.println(f + " " + feature + " " + dataSeq.holdsInTrainingData(feature,i-ell,i)); } } } if (params.debugLvl > 2) { System.out.println("Alpha-i " + alpha_Y_Array[i-base].toString()); System.out.println("Ri " + Ri_Y.toString()); System.out.println("Mi " + Mi_YY.toString()); System.out.println("Beta-i " + beta_Y[i].toString()); } } double lZx = alpha_Y_Array[dataSeq.length()-1-base].zSum(); thisSeqLogli -= lZx; logli += thisSeqLogli; // update grad. for (int f = 0; f < grad.length; f++) grad[f] -= Math.exp(ExpF[f]-lZx); if (noneFired) { System.out.println("WARNING: no features fired in the training set"); } if (thisSeqLogli > 0) { System.out.println("ERROR: something is wrong Pr(y|x) > 1!"); } if (params.debugLvl > 1 || (thisSeqLogli > 0)) { System.out.println("Sequence likelihood " + thisSeqLogli + " " + lZx + " " + Math.exp(lZx)); System.out.println("Last Alpha-i " + alpha_Y_Array[dataSeq.length()-1-base].toString()); } } if (params.debugLvl > 2) { for (int f = 0; f < lambda.length; f++) System.out.print(lambda[f] + " "); System.out.println(" :x"); for (int f = 0; f < lambda.length; f++) System.out.print(grad[f] + " "); System.out.println(" :g"); } if (params.debugLvl > 0) { if (icall == 0) { Util.printDbg("Number of training records " + numRecord); } Util.printDbg("Iter " + icall + " loglikelihood "+logli + " gnorm " + norm(grad) + " xnorm "+ norm(lambda)); } return logli; } catch (Exception e) { e.printStackTrace(); System.exit(0); } return 0; }
diff --git a/autotools/org.eclipse.linuxtools.cdt.autotools.core/src/org/eclipse/linuxtools/internal/cdt/autotools/core/configure/FlagConfigureOption.java b/autotools/org.eclipse.linuxtools.cdt.autotools.core/src/org/eclipse/linuxtools/internal/cdt/autotools/core/configure/FlagConfigureOption.java index b8d7b30f8..300e8ff85 100644 --- a/autotools/org.eclipse.linuxtools.cdt.autotools.core/src/org/eclipse/linuxtools/internal/cdt/autotools/core/configure/FlagConfigureOption.java +++ b/autotools/org.eclipse.linuxtools.cdt.autotools.core/src/org/eclipse/linuxtools/internal/cdt/autotools/core/configure/FlagConfigureOption.java @@ -1,104 +1,106 @@ /******************************************************************************* * Copyright (c) 2011 Red Hat Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.linuxtools.internal.cdt.autotools.core.configure; import java.util.ArrayList; public class FlagConfigureOption extends AbstractConfigurationOption { private String value; private ArrayList<String> children = new ArrayList<String>(); public FlagConfigureOption(String name, AutotoolsConfiguration cfg) { super(name, cfg); this.value = ""; // $NON-NLS-1$ } public FlagConfigureOption(String name, String msgName, AutotoolsConfiguration cfg) { super(name, msgName, cfg); this.value = ""; // $NON-NLS-1$ } @SuppressWarnings("unchecked") private FlagConfigureOption(String name, AutotoolsConfiguration cfg, String value, ArrayList<String> children) { super(name, cfg); this.value = value; this.children = (ArrayList<String>)children.clone(); } public String getParameter() { StringBuffer parm = new StringBuffer(getName()+"=\""); //$NON-NLS-1$ boolean haveParm = false; if (isParmSet()) { + String separator = ""; for (int i = 0; i < children.size(); ++i) { String fvname = children.get(i); IConfigureOption o = cfg.getOption(fvname); if (o.isParmSet()) { if (o instanceof IFlagConfigureValueOption) { - parm.append(" " + ((IFlagConfigureValueOption)o).getFlags()); //$NON-NLS-1$ + parm.append(separator + ((IFlagConfigureValueOption)o).getFlags()); //$NON-NLS-1$ + separator = " "; haveParm = true; } } } if (haveParm) { parm.append("\""); //$NON-NLS-1$ return parm.toString(); } } return ""; //$NON-NLS-1$ } public String getParameterName() { return getName(); } public boolean isParmSet() { for (int i = 0; i < children.size(); ++i) { String s = children.get(i); IConfigureOption o = cfg.getOption(s); if (o.isParmSet()) return true; } return false; } public void setValue(String value) { // can't occur } public IConfigureOption copy(AutotoolsConfiguration config) { FlagConfigureOption f = new FlagConfigureOption(name, config, value, children); return f; } public String getValue() { return value; } public int getType() { return FLAG; } public boolean isFlag() { return true; } public void addChild(String name) { children.add(name); } public ArrayList<String> getChildren() { return children; } }
false
true
public String getParameter() { StringBuffer parm = new StringBuffer(getName()+"=\""); //$NON-NLS-1$ boolean haveParm = false; if (isParmSet()) { for (int i = 0; i < children.size(); ++i) { String fvname = children.get(i); IConfigureOption o = cfg.getOption(fvname); if (o.isParmSet()) { if (o instanceof IFlagConfigureValueOption) { parm.append(" " + ((IFlagConfigureValueOption)o).getFlags()); //$NON-NLS-1$ haveParm = true; } } } if (haveParm) { parm.append("\""); //$NON-NLS-1$ return parm.toString(); } } return ""; //$NON-NLS-1$ }
public String getParameter() { StringBuffer parm = new StringBuffer(getName()+"=\""); //$NON-NLS-1$ boolean haveParm = false; if (isParmSet()) { String separator = ""; for (int i = 0; i < children.size(); ++i) { String fvname = children.get(i); IConfigureOption o = cfg.getOption(fvname); if (o.isParmSet()) { if (o instanceof IFlagConfigureValueOption) { parm.append(separator + ((IFlagConfigureValueOption)o).getFlags()); //$NON-NLS-1$ separator = " "; haveParm = true; } } } if (haveParm) { parm.append("\""); //$NON-NLS-1$ return parm.toString(); } } return ""; //$NON-NLS-1$ }
diff --git a/msv/src/com/sun/msv/verifier/Verifier.java b/msv/src/com/sun/msv/verifier/Verifier.java index 1c89dc97..1ad0dae3 100644 --- a/msv/src/com/sun/msv/verifier/Verifier.java +++ b/msv/src/com/sun/msv/verifier/Verifier.java @@ -1,326 +1,326 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.verifier; import org.xml.sax.*; import org.xml.sax.helpers.NamespaceSupport; import org.relaxng.datatype.Datatype; import java.util.Set; import java.util.Map; import java.util.Iterator; import com.sun.msv.datatype.xsd.StringType; import com.sun.msv.grammar.IDContextProvider; import com.sun.msv.util.StringRef; import com.sun.msv.util.StringPair; import com.sun.msv.util.StartTagInfo; import com.sun.msv.util.DatatypeRef; /** * SAX ContentHandler that verifies incoming SAX event stream. * * This object can be reused to validate multiple documents. * Just be careful NOT to use the same object to validate more than one * documents <b>at the same time</b>. * * @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a> */ public class Verifier extends AbstractVerifier implements IVerifier { protected Acceptor current; private static final class Context { final Context previous; final Acceptor acceptor; final int stringCareLevel; int panicLevel; Context( Context prev, Acceptor acc, int scl, int plv ) { previous=prev; acceptor=acc; stringCareLevel=scl; panicLevel=plv; } }; /** context stack */ Context stack = null; /** current string care level. See Acceptor.getStringCareLevel */ private int stringCareLevel = Acceptor.STRING_STRICT; /** characters that were read (but not processed) */ private StringBuffer text = new StringBuffer(); /** error handler */ protected VerificationErrorHandler errorHandler; public final VerificationErrorHandler getVErrorHandler() { return errorHandler; } /** this flag will be set to true if an error is found */ protected boolean hadError; /** this flag will be set to true after endDocument method is called. */ private boolean isFinished; /** an object used to store start tag information. * the same object is reused. */ private final StartTagInfo sti = new StartTagInfo(null,null,null,null,null); public final boolean isValid() { return !hadError && isFinished; } /** Schema object against which the validation will be done */ protected final DocumentDeclaration docDecl; /** panic level. * * If the level is non-zero, createChildAcceptors will silently recover * from error. This effectively suppresses spurious error messages. * * This value is set to INITIAL_PANIC_LEVEL when first an error is encountered, * and is decreased by successful stepForward and createChildAcceptor. * This value is also propagated to child acceptors. */ protected int panicLevel = 0; private final static int INITIAL_PANIC_LEVEL = 3; public Verifier( DocumentDeclaration documentDecl, VerificationErrorHandler errorHandler ) { this.docDecl = documentDecl; this.errorHandler = errorHandler; } /** this field is used to receive type information of character literals. */ private final DatatypeRef characterType = new DatatypeRef(); public Datatype[] getLastCharacterType() { return characterType.types; } private void verifyText() throws SAXException { if(text.length()!=0) { characterType.types=null; switch( stringCareLevel ) { case Acceptor.STRING_PROHIBITED: // only whitespace is allowed. final int len = text.length(); for( int i=0; i<len; i++ ) { final char ch = text.charAt(i); if( ch!=' ' && ch!='\t' && ch!='\r' && ch!='\n' ) { // error onError( null, localizeMessage( ERR_UNEXPECTED_TEXT, null ) ); break;// recover by ignoring this token } } break; case Acceptor.STRING_STRICT: final String txt = new String(text); if(!current.stepForward( txt, this, null, characterType )) { // error // diagnose error, if possible StringRef err = new StringRef(); characterType.types=null; current.stepForward( txt, this, err, characterType ); // report an error onError( err, localizeMessage( ERR_UNEXPECTED_TEXT, null ) ); } break; case Acceptor.STRING_IGNORE: // if STRING_IGNORE, no text should be appended. default: throw new Error(); //assertion failed } text = new StringBuffer(); } } public void startElement( String namespaceUri, String localName, String qName, Attributes atts ) throws SAXException { super.startElement(namespaceUri,localName,qName,atts); if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("\n-- startElement("+qName+")" + locator.getLineNumber()+":"+locator.getColumnNumber() ); verifyText(); // verify PCDATA first. // push context stack = new Context( stack, current, stringCareLevel, panicLevel ); sti.reinit(namespaceUri, localName, qName, atts, this ); // get Acceptor that will be used to validate the contents of this element. - Acceptor next = current.createChildAcceptor(sti,ref); + Acceptor next = current.createChildAcceptor(sti,null); if( next==null ) { // no child element matchs this one if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("-- no children accepted: error recovery"); // let acceptor recover from this error. StringRef ref = new StringRef(); - next = getNextAcceptor(sti,ref); + next = current.createChildAcceptor(sti,ref); ValidityViolation vv = onError( ref, localizeMessage( ERR_UNEXPECTED_STARTTAG, new Object[]{qName} ) ); if( next==null ) { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("-- unable to recover"); throw new ValidationUnrecoverableException(vv); } } else panicLevel = Math.max( panicLevel-1, 0 ); stack.panicLevel = panicLevel; // back-patching. stringCareLevel = next.getStringCareLevel(); if( stringCareLevel==Acceptor.STRING_IGNORE ) characterType.types = new Datatype[]{StringType.theInstance}; current = next; } public void endElement( String namespaceUri, String localName, String qName ) throws SAXException { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("\n-- endElement("+qName+")" + locator.getLineNumber()+":"+locator.getColumnNumber() ); verifyText(); if( !current.isAcceptState(null) && panicLevel==0 ) { // error diagnosis StringRef errRef = new StringRef(); current.isAcceptState(errRef); onError( errRef, localizeMessage( ERR_UNCOMPLETED_CONTENT,new Object[]{qName} ) ); // error recovery: pretend as if this state is satisfied // fall through is enough } Acceptor child = current; // pop context current = stack.acceptor; stringCareLevel = stack.stringCareLevel; panicLevel = Math.max( panicLevel, stack.panicLevel ); stack = stack.previous; if(!current.stepForward( child, null )) {// error StringRef ref = new StringRef(); current.stepForward( child, ref ); // force recovery onError( ref, localizeMessage( ERR_UNEXPECTED_ELEMENT, new Object[]{qName} ) ); } else panicLevel = Math.max( panicLevel-1, 0 ); super.endElement( namespaceUri, localName, qName ); } /** * signals an error. * * This method can be overrided by the derived class to provide different behavior. */ protected ValidityViolation onError( StringRef ref, String defaultMsg ) throws SAXException { ValidityViolation vv; hadError = true; if( ref!=null && ref.str!=null ) // error message is available vv = new ValidityViolation(locator,ref.str); else // no error message is avaiable, use default. vv = new ValidityViolation( locator, defaultMsg ); if( errorHandler!=null && panicLevel==0 ) errorHandler.onError(vv); panicLevel = INITIAL_PANIC_LEVEL; return vv; } public Object getCurrentElementType() { return current.getOwnerType(); } public void characters( char[] buf, int start, int len ) throws SAXException { if( stringCareLevel!=Acceptor.STRING_IGNORE ) text.append(buf,start,len); } public void ignorableWhitespace( char[] buf, int start, int len ) throws SAXException { if( stringCareLevel!=Acceptor.STRING_IGNORE && stringCareLevel!=Acceptor.STRING_PROHIBITED ) // white space is allowed even if the current mode is STRING_PROHIBITED. text.append(buf,start,len); } protected void init() { super.init(); hadError=false; isFinished=false; } public void startDocument() { // reset everything. // since Verifier maybe reused, initialization is better done here // rather than constructor. init(); // if Verifier is used without "divide&validate", // this method is called and the initial acceptor // is set by this method. // When Verifier is used in IslandVerifierImpl, // then initial acceptor is set at the constructor // and this method is not called. current = docDecl.createAcceptor(); } public void endDocument() throws SAXException { // ID/IDREF check Iterator itr = idrefs.keySet().iterator(); while( itr.hasNext() ) { StringPair symbolSpace = (StringPair)itr.next(); Set refs = (Set)idrefs.get(symbolSpace); Set keys = (Set)ids.get(symbolSpace); if(keys==null || !keys.containsAll(refs)) { hadError = true; Iterator jtr = refs.iterator(); while( jtr.hasNext() ) { Object idref = jtr.next(); if(keys==null || !keys.contains(idref)) { if( symbolSpace.localName.length()==0 && symbolSpace.namespaceURI.length()==0 ) onError( null, localizeMessage( ERR_UNSOLD_IDREF, new Object[]{idref} ) ); else onError( null, localizeMessage( ERR_UNSOLD_KEYREF, new Object[]{idref,symbolSpace} ) ); } } } } isFinished=true; } public static String localizeMessage( String propertyName, Object[] args ) { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.verifier.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } public static final String ERR_UNEXPECTED_TEXT = // arg:0 "Verifier.Error.UnexpectedText"; public static final String ERR_UNEXPECTED_STARTTAG = // arg:1 "Verifier.Error.UnexpectedStartTag"; public static final String ERR_UNCOMPLETED_CONTENT = // arg:1 "Verifier.Error.UncompletedContent"; public static final String ERR_UNEXPECTED_ELEMENT = // arg:1 "Verifier.Error.UnexpectedElement"; public static final String ERR_UNSOLD_IDREF = // arg:1 "Verifier.Error.UnsoldIDREF"; public static final String ERR_UNSOLD_KEYREF = // arg:1 "Verifier.Error.UnsoldKeyref"; }
false
true
public void startElement( String namespaceUri, String localName, String qName, Attributes atts ) throws SAXException { super.startElement(namespaceUri,localName,qName,atts); if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("\n-- startElement("+qName+")" + locator.getLineNumber()+":"+locator.getColumnNumber() ); verifyText(); // verify PCDATA first. // push context stack = new Context( stack, current, stringCareLevel, panicLevel ); sti.reinit(namespaceUri, localName, qName, atts, this ); // get Acceptor that will be used to validate the contents of this element. Acceptor next = current.createChildAcceptor(sti,ref); if( next==null ) { // no child element matchs this one if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("-- no children accepted: error recovery"); // let acceptor recover from this error. StringRef ref = new StringRef(); next = getNextAcceptor(sti,ref); ValidityViolation vv = onError( ref, localizeMessage( ERR_UNEXPECTED_STARTTAG, new Object[]{qName} ) ); if( next==null ) { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("-- unable to recover"); throw new ValidationUnrecoverableException(vv); } } else panicLevel = Math.max( panicLevel-1, 0 ); stack.panicLevel = panicLevel; // back-patching. stringCareLevel = next.getStringCareLevel(); if( stringCareLevel==Acceptor.STRING_IGNORE ) characterType.types = new Datatype[]{StringType.theInstance}; current = next; }
public void startElement( String namespaceUri, String localName, String qName, Attributes atts ) throws SAXException { super.startElement(namespaceUri,localName,qName,atts); if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("\n-- startElement("+qName+")" + locator.getLineNumber()+":"+locator.getColumnNumber() ); verifyText(); // verify PCDATA first. // push context stack = new Context( stack, current, stringCareLevel, panicLevel ); sti.reinit(namespaceUri, localName, qName, atts, this ); // get Acceptor that will be used to validate the contents of this element. Acceptor next = current.createChildAcceptor(sti,null); if( next==null ) { // no child element matchs this one if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("-- no children accepted: error recovery"); // let acceptor recover from this error. StringRef ref = new StringRef(); next = current.createChildAcceptor(sti,ref); ValidityViolation vv = onError( ref, localizeMessage( ERR_UNEXPECTED_STARTTAG, new Object[]{qName} ) ); if( next==null ) { if( com.sun.msv.driver.textui.Debug.debug ) System.out.println("-- unable to recover"); throw new ValidationUnrecoverableException(vv); } } else panicLevel = Math.max( panicLevel-1, 0 ); stack.panicLevel = panicLevel; // back-patching. stringCareLevel = next.getStringCareLevel(); if( stringCareLevel==Acceptor.STRING_IGNORE ) characterType.types = new Datatype[]{StringType.theInstance}; current = next; }
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java index 3096232..b0ff13f 100644 --- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java +++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java @@ -1,176 +1,178 @@ /* * YUI Compressor * Author: Julien Lecomte <[email protected]> * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Code licensed under the BSD License: * http://developer.yahoo.net/yui/license.txt * * This code is a port of Isaac Schlueter's cssmin utility. */ package com.yahoo.platform.yui.compressor; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.regex.Pattern; import java.util.regex.Matcher; public class CssCompressor { private StringBuffer srcsb = new StringBuffer(); public CssCompressor(Reader in) throws IOException { // Read the stream... int c; while ((c = in.read()) != -1) { srcsb.append((char) c); } } public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... startIndex = 0; boolean iemac = false; sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); - if (endIndex >= startIndex + 2) { + if (endIndex < 0) { + sb.delete(startIndex, sb.length()); + } else if (endIndex >= startIndex + 2) { if (sb.charAt(endIndex-1) == '\\') { // Looks like a comment to hide rules from IE Mac. // Leave this comment, and the following one, alone... startIndex = endIndex + 2; iemac = true; } else if (iemac) { startIndex = endIndex + 2; iemac = false; } else { sb.delete(startIndex, endIndex + 2); } } } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Make a pseudo class for the Box Model Hack css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___"); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6)) && m.group(7).equalsIgnoreCase(m.group(8))) { m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace the pseudo class for the Box Model Hack css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\""); // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); } }
true
true
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... startIndex = 0; boolean iemac = false; sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex >= startIndex + 2) { if (sb.charAt(endIndex-1) == '\\') { // Looks like a comment to hide rules from IE Mac. // Leave this comment, and the following one, alone... startIndex = endIndex + 2; iemac = true; } else if (iemac) { startIndex = endIndex + 2; iemac = false; } else { sb.delete(startIndex, endIndex + 2); } } } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Make a pseudo class for the Box Model Hack css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___"); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6)) && m.group(7).equalsIgnoreCase(m.group(8))) { m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace the pseudo class for the Box Model Hack css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\""); // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... startIndex = 0; boolean iemac = false; sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex < 0) { sb.delete(startIndex, sb.length()); } else if (endIndex >= startIndex + 2) { if (sb.charAt(endIndex-1) == '\\') { // Looks like a comment to hide rules from IE Mac. // Leave this comment, and the following one, alone... startIndex = endIndex + 2; iemac = true; } else if (iemac) { startIndex = endIndex + 2; iemac = false; } else { sb.delete(startIndex, endIndex + 2); } } } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Make a pseudo class for the Box Model Hack css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___"); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6)) && m.group(7).equalsIgnoreCase(m.group(8))) { m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace the pseudo class for the Box Model Hack css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\""); // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
diff --git a/src/monnef/core/common/ContainerRegistry.java b/src/monnef/core/common/ContainerRegistry.java index a177914..d94c84f 100644 --- a/src/monnef/core/common/ContainerRegistry.java +++ b/src/monnef/core/common/ContainerRegistry.java @@ -1,305 +1,310 @@ /* * Jaffas and more! * author: monnef */ package monnef.core.common; import monnef.core.MonnefCorePlugin; import monnef.core.block.ContainerMonnefCore; import monnef.core.client.GuiContainerMonnefCore; import monnef.core.external.eu.infomas.annotation.AnnotationDetector; import monnef.core.utils.ReflectionTools; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.tileentity.TileEntity; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.text.DecimalFormat; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static monnef.core.MonnefCorePlugin.Log; public class ContainerRegistry { public static final String CANNOT_INSTANTIATE_CONTAINER = "Cannot instantiate container."; private static HashMap<Class<? extends TileEntity>, MachineItem> db = new HashMap<Class<? extends TileEntity>, MachineItem>(); private static boolean filledFromAnnotationsServer = false; private static boolean filledFromAnnotationsClient = false; private static DecimalFormat decimalFormatter = new DecimalFormat("#.##"); @SuppressWarnings("unchecked") public static void fillRegistrationsFromAnnotations(boolean clientSide) { if (!clientSide) { if (filledFromAnnotationsServer) throw new RuntimeException("Server registry are already filled from annotations."); filledFromAnnotationsServer = true; } else { if (filledFromAnnotationsClient) throw new RuntimeException("Client registry are already filled from annotations."); filledFromAnnotationsClient = true; } final HashSet<Class<?>> result = new HashSet<Class<?>>(); final AnnotationDetector.TypeReporter reporter = new AnnotationDetector.TypeReporter() { @SuppressWarnings("unchecked") @Override public Class<? extends Annotation>[] annotations() { return new Class[]{ContainerTag.class}; } @Override public void reportTypeAnnotation(Class<? extends Annotation> annotation, String className) { Log.printFinest(String.format("Discovered ContainerTag annotation on class: %s", className)); try { result.add(this.getClass().getClassLoader().loadClass(className)); } catch (ClassNotFoundException e) { Log.printWarning("Container registry: unable to load \"" + className + "\"!"); } } }; final AnnotationDetector cf = new AnnotationDetector(reporter); long timeStart = System.currentTimeMillis(); try { cf.detect(); long timeStop = System.currentTimeMillis(); Log.printFine(String.format("%s-side annotation class-path scanning for ContainerTag took %ss", clientSide ? "Client" : "Server", decimalFormatter.format((timeStop - timeStart) / 1000f))); timeStart = System.currentTimeMillis(); File file = new File(MonnefCorePlugin.getMcPath() + "/mods/"); if (file.isDirectory()) { for (File f : file.listFiles()) { Log.printFinest(String.format("Scanning file: %s", f.getName())); - cf.detect(f); + try { + cf.detect(f); + } catch (IOException e) { + Log.printWarning(String.format("Cannot process file: '%s'", f.getName())); + e.printStackTrace(); + } } } timeStop = System.currentTimeMillis(); Log.printFine(String.format("%s-side annotation mods directory scanning for ContainerTag took %ss", clientSide ? "Client" : "Server", decimalFormatter.format((timeStop - timeStart) / 1000f))); } catch (IOException e) { Log.printSevere("Encountered IO error:" + e.getMessage()); e.printStackTrace(); } for (Class<?> c : result) { ContainerTag tag = c.getAnnotation(ContainerTag.class); if (TileEntity.class.isAssignableFrom(c)) { Class<TileEntity> tec = (Class<TileEntity>) c; if (clientSide) { if (!"".equals(tag.guiClassName())) { try { Class<? extends GuiContainerMonnefCore> clazz = (Class<? extends GuiContainerMonnefCore>) ContainerRegistry.class.getClassLoader().loadClass(tag.guiClassName()); registerOnClientInternal(tec, clazz); } catch (ClassNotFoundException e) { Log.printWarning("Client-side registration failed, class \"" + tag.guiClassName() + "\" cannot be loaded. TE class: " + tec.getName()); } } } else { if (!"".equals(tag.containerClassName())) { try { Class<? extends ContainerMonnefCore> clazz = (Class<? extends ContainerMonnefCore>) ContainerRegistry.class.getClassLoader().loadClass(tag.containerClassName()); registerInternal(tec, clazz); } catch (ClassNotFoundException e) { Log.printWarning("Registration failed, class \"" + tag.containerClassName() + "\" cannot be loaded. TE class: " + tec.getName()); } } } } else { Log.printWarning(String.format("Class %s is annotated with ContainerTag but is not TileEntity, mistake?", c.getName())); } } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface ContainerTag { int slotsCount(); int outputSlotsCount() default 1; int inputSlotsCount() default -1; String guiClassName() default ""; String containerClassName() default ""; } public static class ContainerDescriptor { private final int slotsCount; private final int outputSlotsCount; private final int inputSlotsCount; public ContainerDescriptor(ContainerTag tag) { slotsCount = tag.slotsCount(); outputSlotsCount = tag.outputSlotsCount(); inputSlotsCount = tag.inputSlotsCount() == -1 ? slotsCount - outputSlotsCount : tag.inputSlotsCount(); } public int getSlotsCount() { return slotsCount; } public int getOutputSlotsCount() { return outputSlotsCount; } public int getInputSlotsCount() { return inputSlotsCount; } public int getStartIndexOfOutput() { return getSlotsCount() - getOutputSlotsCount(); } } public static class MachineItem { public final Class<? extends TileEntity> tileClass; public final Class<? extends ContainerMonnefCore> containerClass; private Class<?> guiClass; // GuiContainerBasicProcessingMachine public final ContainerDescriptor containerPrototype; private Constructor<?> guiConstructor; // GuiContainerBasicProcessingMachine public final Constructor<? extends ContainerMonnefCore> containerConstructor; private MachineItem(Class<? extends TileEntity> tileClass, Class<? extends ContainerMonnefCore> containerClass, ContainerDescriptor containerPrototype) { this.tileClass = tileClass; this.containerClass = containerClass; this.containerPrototype = containerPrototype; if (containerClass.getConstructors().length != 1) { throw new RuntimeException("Multiple constructors of container class."); } Constructor<?> constructor = containerClass.getConstructors()[0]; if (constructor.getParameterTypes().length != 2) { throw new RuntimeException("Wrong count of parameters of container constructor."); } if (!InventoryPlayer.class.isAssignableFrom(constructor.getParameterTypes()[0]) || !TileEntity.class.isAssignableFrom(constructor.getParameterTypes()[1])) { throw new RuntimeException("Incorrect type of parameters of container constructor."); } //this.containerConstructor = containerClass.getConstructor(InventoryPlayer.class, TileEntity.class); this.containerConstructor = (Constructor<? extends ContainerMonnefCore>) constructor; } private void setGuiConstructor(Constructor<?> guiConstructor) { if (this.guiConstructor != null) throw new RuntimeException("GUI constructor already set"); this.guiConstructor = guiConstructor; } public void setGuiClass(Class<?> guiClass) { this.guiClass = guiClass; if (guiClass != null) { if (guiClass.getConstructors().length != 1) { throw new RuntimeException("Multiple constructors of GUI class."); } Constructor<?> constructor = guiClass.getConstructors()[0]; if (constructor.getParameterTypes().length != 3) { throw new RuntimeException("Wrong count of parameters of GUI constructor."); } if (!InventoryPlayer.class.isAssignableFrom(constructor.getParameterTypes()[0]) || !TileEntity.class.isAssignableFrom(constructor.getParameterTypes()[1]) || !ContainerMonnefCore.class.isAssignableFrom(constructor.getParameterTypes()[2])) { throw new RuntimeException("Incorrect type of parameters of GUI constructor."); } setGuiConstructor(constructor); } else setGuiConstructor(null); } public Constructor<?> getGuiConstructor() { return guiConstructor; } public Class<?> getGuiClass() { return guiClass; } } @SuppressWarnings("deprecation") private static void registerInternal(Class<? extends TileEntity> clazz, Class<? extends ContainerMonnefCore> container) { register(clazz, container); } @SuppressWarnings("deprecation") private static void registerOnClientInternal(Class<? extends TileEntity> clazz, Class<?> gui) { registerOnClient(clazz, gui); } @Deprecated public static void register(Class<? extends TileEntity> clazz, Class<? extends ContainerMonnefCore> container) { if (db.containsKey(clazz)) { throw new RuntimeException("containerPrototype already contains this class, cannot re-register"); } ContainerTag tag = ReflectionTools.findAnnotation(ContainerTag.class, clazz); if (tag == null) { throw new RuntimeException(ContainerTag.class.getSimpleName() + " not found on " + clazz.getSimpleName()); } db.put(clazz, new MachineItem(clazz, container, new ContainerDescriptor(tag))); } @Deprecated public static void registerOnClient(Class<? extends TileEntity> clazz, Class<?> gui) { MachineItem item = db.get(clazz); if (item == null) { throw new RuntimeException(String.format("Registering GUI container with unknown TE. TE: %s, GUI: %s", clazz.getName(), gui.getName())); } if (!GuiContainerMonnefCore.class.isAssignableFrom(gui)) { throw new RuntimeException("Class doesn't inherit from proper ancestor!"); } item.setGuiClass(gui); } public static void assertAllItemsHasGuiClass() { for (Map.Entry<Class<? extends TileEntity>, MachineItem> item : db.entrySet()) { if (item.getValue().getGuiClass() == null) { throw new RuntimeException("TE " + item.getKey().getSimpleName() + " is missing GUI mapping."); } } } public static ContainerDescriptor getContainerPrototype(Class<? extends TileEntity> clazz) { if (!db.containsKey(clazz)) { throw new RuntimeException("Query for not registered TE named " + clazz.getSimpleName()); } return db.get(clazz).containerPrototype; } public static Collection<Class<? extends TileEntity>> getTileClasses() { return db.keySet(); } public static ContainerMonnefCore createContainer(TileEntity tile, InventoryPlayer inventory) { try { return db.get(tile.getClass()).containerConstructor.newInstance(inventory, tile); } catch (Throwable e) { throw new RuntimeException("Cannot create new container for tile class: " + tile.getClass().getSimpleName(), e); } } public static MachineItem getItem(Class tileClass) { return db.get(tileClass); } public static boolean containsRegistration(TileEntity tile) { if (tile == null) return false; return db.containsKey(tile.getClass()); } public static Object createGui(TileEntity tile, InventoryPlayer inventory) { try { return ContainerRegistry.getItem(tile.getClass()).getGuiConstructor().newInstance(inventory, tile, ContainerRegistry.createContainer(tile, inventory)); } catch (Throwable e) { throw new RuntimeException("Cannot create new GUI for container for tile class: " + tile.getClass().getSimpleName(), e); } } }
true
true
public static void fillRegistrationsFromAnnotations(boolean clientSide) { if (!clientSide) { if (filledFromAnnotationsServer) throw new RuntimeException("Server registry are already filled from annotations."); filledFromAnnotationsServer = true; } else { if (filledFromAnnotationsClient) throw new RuntimeException("Client registry are already filled from annotations."); filledFromAnnotationsClient = true; } final HashSet<Class<?>> result = new HashSet<Class<?>>(); final AnnotationDetector.TypeReporter reporter = new AnnotationDetector.TypeReporter() { @SuppressWarnings("unchecked") @Override public Class<? extends Annotation>[] annotations() { return new Class[]{ContainerTag.class}; } @Override public void reportTypeAnnotation(Class<? extends Annotation> annotation, String className) { Log.printFinest(String.format("Discovered ContainerTag annotation on class: %s", className)); try { result.add(this.getClass().getClassLoader().loadClass(className)); } catch (ClassNotFoundException e) { Log.printWarning("Container registry: unable to load \"" + className + "\"!"); } } }; final AnnotationDetector cf = new AnnotationDetector(reporter); long timeStart = System.currentTimeMillis(); try { cf.detect(); long timeStop = System.currentTimeMillis(); Log.printFine(String.format("%s-side annotation class-path scanning for ContainerTag took %ss", clientSide ? "Client" : "Server", decimalFormatter.format((timeStop - timeStart) / 1000f))); timeStart = System.currentTimeMillis(); File file = new File(MonnefCorePlugin.getMcPath() + "/mods/"); if (file.isDirectory()) { for (File f : file.listFiles()) { Log.printFinest(String.format("Scanning file: %s", f.getName())); cf.detect(f); } } timeStop = System.currentTimeMillis(); Log.printFine(String.format("%s-side annotation mods directory scanning for ContainerTag took %ss", clientSide ? "Client" : "Server", decimalFormatter.format((timeStop - timeStart) / 1000f))); } catch (IOException e) { Log.printSevere("Encountered IO error:" + e.getMessage()); e.printStackTrace(); } for (Class<?> c : result) { ContainerTag tag = c.getAnnotation(ContainerTag.class); if (TileEntity.class.isAssignableFrom(c)) { Class<TileEntity> tec = (Class<TileEntity>) c; if (clientSide) { if (!"".equals(tag.guiClassName())) { try { Class<? extends GuiContainerMonnefCore> clazz = (Class<? extends GuiContainerMonnefCore>) ContainerRegistry.class.getClassLoader().loadClass(tag.guiClassName()); registerOnClientInternal(tec, clazz); } catch (ClassNotFoundException e) { Log.printWarning("Client-side registration failed, class \"" + tag.guiClassName() + "\" cannot be loaded. TE class: " + tec.getName()); } } } else { if (!"".equals(tag.containerClassName())) { try { Class<? extends ContainerMonnefCore> clazz = (Class<? extends ContainerMonnefCore>) ContainerRegistry.class.getClassLoader().loadClass(tag.containerClassName()); registerInternal(tec, clazz); } catch (ClassNotFoundException e) { Log.printWarning("Registration failed, class \"" + tag.containerClassName() + "\" cannot be loaded. TE class: " + tec.getName()); } } } } else { Log.printWarning(String.format("Class %s is annotated with ContainerTag but is not TileEntity, mistake?", c.getName())); } } }
public static void fillRegistrationsFromAnnotations(boolean clientSide) { if (!clientSide) { if (filledFromAnnotationsServer) throw new RuntimeException("Server registry are already filled from annotations."); filledFromAnnotationsServer = true; } else { if (filledFromAnnotationsClient) throw new RuntimeException("Client registry are already filled from annotations."); filledFromAnnotationsClient = true; } final HashSet<Class<?>> result = new HashSet<Class<?>>(); final AnnotationDetector.TypeReporter reporter = new AnnotationDetector.TypeReporter() { @SuppressWarnings("unchecked") @Override public Class<? extends Annotation>[] annotations() { return new Class[]{ContainerTag.class}; } @Override public void reportTypeAnnotation(Class<? extends Annotation> annotation, String className) { Log.printFinest(String.format("Discovered ContainerTag annotation on class: %s", className)); try { result.add(this.getClass().getClassLoader().loadClass(className)); } catch (ClassNotFoundException e) { Log.printWarning("Container registry: unable to load \"" + className + "\"!"); } } }; final AnnotationDetector cf = new AnnotationDetector(reporter); long timeStart = System.currentTimeMillis(); try { cf.detect(); long timeStop = System.currentTimeMillis(); Log.printFine(String.format("%s-side annotation class-path scanning for ContainerTag took %ss", clientSide ? "Client" : "Server", decimalFormatter.format((timeStop - timeStart) / 1000f))); timeStart = System.currentTimeMillis(); File file = new File(MonnefCorePlugin.getMcPath() + "/mods/"); if (file.isDirectory()) { for (File f : file.listFiles()) { Log.printFinest(String.format("Scanning file: %s", f.getName())); try { cf.detect(f); } catch (IOException e) { Log.printWarning(String.format("Cannot process file: '%s'", f.getName())); e.printStackTrace(); } } } timeStop = System.currentTimeMillis(); Log.printFine(String.format("%s-side annotation mods directory scanning for ContainerTag took %ss", clientSide ? "Client" : "Server", decimalFormatter.format((timeStop - timeStart) / 1000f))); } catch (IOException e) { Log.printSevere("Encountered IO error:" + e.getMessage()); e.printStackTrace(); } for (Class<?> c : result) { ContainerTag tag = c.getAnnotation(ContainerTag.class); if (TileEntity.class.isAssignableFrom(c)) { Class<TileEntity> tec = (Class<TileEntity>) c; if (clientSide) { if (!"".equals(tag.guiClassName())) { try { Class<? extends GuiContainerMonnefCore> clazz = (Class<? extends GuiContainerMonnefCore>) ContainerRegistry.class.getClassLoader().loadClass(tag.guiClassName()); registerOnClientInternal(tec, clazz); } catch (ClassNotFoundException e) { Log.printWarning("Client-side registration failed, class \"" + tag.guiClassName() + "\" cannot be loaded. TE class: " + tec.getName()); } } } else { if (!"".equals(tag.containerClassName())) { try { Class<? extends ContainerMonnefCore> clazz = (Class<? extends ContainerMonnefCore>) ContainerRegistry.class.getClassLoader().loadClass(tag.containerClassName()); registerInternal(tec, clazz); } catch (ClassNotFoundException e) { Log.printWarning("Registration failed, class \"" + tag.containerClassName() + "\" cannot be loaded. TE class: " + tec.getName()); } } } } else { Log.printWarning(String.format("Class %s is annotated with ContainerTag but is not TileEntity, mistake?", c.getName())); } } }
diff --git a/nifty-examples/src/main/java/de/lessvoid/nifty/examples/defaultcontrols/tabs/TabsControlDialogController.java b/nifty-examples/src/main/java/de/lessvoid/nifty/examples/defaultcontrols/tabs/TabsControlDialogController.java index 41618e66..126c2c18 100644 --- a/nifty-examples/src/main/java/de/lessvoid/nifty/examples/defaultcontrols/tabs/TabsControlDialogController.java +++ b/nifty-examples/src/main/java/de/lessvoid/nifty/examples/defaultcontrols/tabs/TabsControlDialogController.java @@ -1,70 +1,68 @@ package de.lessvoid.nifty.examples.defaultcontrols.tabs; import java.util.Properties; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.builder.PanelBuilder; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.Tabs; import de.lessvoid.nifty.controls.tabs.TabControl; import de.lessvoid.nifty.controls.tabs.builder.TabBuilder; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.examples.defaultcontrols.common.CommonBuilders; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.xml.xpp3.Attributes; /** * The TabsControlDialogController registers a new control with Nifty * that represents the whole Dialog. This gives us later an appropriate * ControlBuilder to actual construct the Dialog (as a control). * @author ractoc */ public class TabsControlDialogController implements Controller { private Tabs tabs; private static CommonBuilders builders = new CommonBuilders(); @Override public void bind( final Nifty nifty, final Screen screen, final Element element, final Properties parameter, final Attributes controlDefinitionAttributes) { this.tabs = screen.findNiftyControl("tabs", Tabs.class); - Element tab1 = new TabBuilder("tab_1") {{ + Element tab1 = new TabBuilder("tab_1", "Tab 1") {{ panel(new PanelBuilder() {{ childLayoutHorizontal(); control(builders.createLabel("Tab 1")); }}); - }}.build(nifty, screen, element); - tab1.getControl(TabControl.class).setCaption("Tab 1"); + }}.build(nifty, screen, this.tabs.getElement()); tabs.addTab(tab1); - Element tab2 = new TabBuilder("tab_2") {{ + Element tab2 = new TabBuilder("tab_2", "Tab 2") {{ panel(new PanelBuilder() {{ childLayoutHorizontal(); control(builders.createLabel("Tab 2")); }}); - }}.build(nifty, screen, element); - tab1.getControl(TabControl.class).setCaption("Tab 2"); + }}.build(nifty, screen, this.tabs.getElement()); tabs.addTab(tab2); } @Override public void init(final Properties parameter, final Attributes controlDefinitionAttributes) { } @Override public void onStartScreen() { } @Override public void onFocus(final boolean getFocus) { } @Override public boolean inputEvent(final NiftyInputEvent inputEvent) { return false; } }
false
true
public void bind( final Nifty nifty, final Screen screen, final Element element, final Properties parameter, final Attributes controlDefinitionAttributes) { this.tabs = screen.findNiftyControl("tabs", Tabs.class); Element tab1 = new TabBuilder("tab_1") {{ panel(new PanelBuilder() {{ childLayoutHorizontal(); control(builders.createLabel("Tab 1")); }}); }}.build(nifty, screen, element); tab1.getControl(TabControl.class).setCaption("Tab 1"); tabs.addTab(tab1); Element tab2 = new TabBuilder("tab_2") {{ panel(new PanelBuilder() {{ childLayoutHorizontal(); control(builders.createLabel("Tab 2")); }}); }}.build(nifty, screen, element); tab1.getControl(TabControl.class).setCaption("Tab 2"); tabs.addTab(tab2); }
public void bind( final Nifty nifty, final Screen screen, final Element element, final Properties parameter, final Attributes controlDefinitionAttributes) { this.tabs = screen.findNiftyControl("tabs", Tabs.class); Element tab1 = new TabBuilder("tab_1", "Tab 1") {{ panel(new PanelBuilder() {{ childLayoutHorizontal(); control(builders.createLabel("Tab 1")); }}); }}.build(nifty, screen, this.tabs.getElement()); tabs.addTab(tab1); Element tab2 = new TabBuilder("tab_2", "Tab 2") {{ panel(new PanelBuilder() {{ childLayoutHorizontal(); control(builders.createLabel("Tab 2")); }}); }}.build(nifty, screen, this.tabs.getElement()); tabs.addTab(tab2); }
diff --git a/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java b/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java index 55ba463..7112cbb 100644 --- a/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java +++ b/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java @@ -1,256 +1,256 @@ /* * Copyright (c) 2008-2009, Motorola, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the Motorola, Inc. nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.android.bluetooth.opp; import com.android.bluetooth.R; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import android.app.Activity; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevicePicker; import android.content.Intent; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.provider.Settings; /** * This class is designed to act as the entry point of handling the share intent * via BT from other APPs. and also make "Bluetooth" available in sharing method * selection dialog. */ public class BluetoothOppLauncherActivity extends Activity { private static final String TAG = "BluetoothLauncherActivity"; private static final boolean D = Constants.DEBUG; private static final boolean V = Constants.VERBOSE; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String action = intent.getAction(); BluetoothDevice device = null; - boolean isHandover = true; + boolean isHandover = false; if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) { /* * Other application is trying to share a file via Bluetooth, * probably Pictures, videos, or vCards. The Intent should contain * an EXTRA_STREAM with the data to attach. */ if (intent.getBooleanExtra(Constants.EXTRA_CONNECTION_HANDOVER, false)) { device = (BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); isHandover = true; } if (action.equals(Intent.ACTION_SEND)) { // TODO: handle type == null case String type = intent.getType(); Uri stream = (Uri)intent.getParcelableExtra(Intent.EXTRA_STREAM); CharSequence extra_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // If we get ACTION_SEND intent with EXTRA_STREAM, we'll use the // uri data; // If we get ACTION_SEND intent without EXTRA_STREAM, but with // EXTRA_TEXT, we will try send this TEXT out; Currently in // Browser, share one link goes to this case; if (stream != null && type != null) { if (V) Log.v(TAG, "Get ACTION_SEND intent: Uri = " + stream + "; mimetype = " + type); // Save type/stream, will be used when adding transfer // session to DB. BluetoothOppManager.getInstance(this).saveSendingFileInfo(type, stream.toString(), isHandover); } else if (extra_text != null && type != null) { if (V) Log.v(TAG, "Get ACTION_SEND intent with Extra_text = " + extra_text.toString() + "; mimetype = " + type); Uri fileUri = creatFileForSharedContent(this, extra_text); if (fileUri != null) { BluetoothOppManager.getInstance(this).saveSendingFileInfo(type, fileUri.toString(), isHandover); } } else { Log.e(TAG, "type is null; or sending file URI is null"); finish(); return; } } else if (action.equals(Intent.ACTION_SEND_MULTIPLE)) { ArrayList<Uri> uris = new ArrayList<Uri>(); String mimeType = intent.getType(); uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (mimeType != null && uris != null) { if (V) Log.v(TAG, "Get ACTION_SHARE_MULTIPLE intent: uris " + uris + "\n Type= " + mimeType); BluetoothOppManager.getInstance(this).saveSendingFileInfo(mimeType, uris, isHandover); } else { Log.e(TAG, "type is null; or sending files URIs are null"); finish(); return; } } if (!isBluetoothAllowed()) { Intent in = new Intent(this, BluetoothOppBtErrorActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); in.putExtra("title", this.getString(R.string.airplane_error_title)); in.putExtra("content", this.getString(R.string.airplane_error_msg)); this.startActivity(in); finish(); return; } // TODO: In the future, we may send intent to DevicePickerActivity // directly, // and let DevicePickerActivity to handle Bluetooth Enable. if (!BluetoothOppManager.getInstance(this).isEnabled()) { if (V) Log.v(TAG, "Prepare Enable BT!! "); Intent in = new Intent(this, BluetoothOppBtEnableActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(in); } else if (device == null) { if (V) Log.v(TAG, "BT already enabled!! "); Intent in1 = new Intent(BluetoothDevicePicker.ACTION_LAUNCH); in1.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); in1.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false); in1.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE, BluetoothDevicePicker.FILTER_TYPE_TRANSFER); in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_PACKAGE, Constants.THIS_PACKAGE_NAME); in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_CLASS, BluetoothOppReceiver.class.getName()); this.startActivity(in1); } else { // we already know where to send to BluetoothOppManager.getInstance(this).startTransfer(device); } } else if (action.equals(Constants.ACTION_OPEN)) { Uri uri = getIntent().getData(); if (V) Log.v(TAG, "Get ACTION_OPEN intent: Uri = " + uri); Intent intent1 = new Intent(); intent1.setAction(action); intent1.setClassName(Constants.THIS_PACKAGE_NAME, BluetoothOppReceiver.class.getName()); intent1.setData(uri); this.sendBroadcast(intent1); } finish(); } /* Returns true if Bluetooth is allowed given current airplane mode settings. */ private final boolean isBluetoothAllowed() { final ContentResolver resolver = this.getContentResolver(); // Check if airplane mode is on final boolean isAirplaneModeOn = Settings.System.getInt(resolver, Settings.System.AIRPLANE_MODE_ON, 0) == 1; if (!isAirplaneModeOn) { return true; } // Check if airplane mode matters final String airplaneModeRadios = Settings.System.getString(resolver, Settings.System.AIRPLANE_MODE_RADIOS); final boolean isAirplaneSensitive = airplaneModeRadios == null ? true : airplaneModeRadios.contains(Settings.System.RADIO_BLUETOOTH); if (!isAirplaneSensitive) { return true; } // Check if Bluetooth may be enabled in airplane mode final String airplaneModeToggleableRadios = Settings.System.getString(resolver, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS); final boolean isAirplaneToggleable = airplaneModeToggleableRadios == null ? false : airplaneModeToggleableRadios.contains(Settings.System.RADIO_BLUETOOTH); if (isAirplaneToggleable) { return true; } // If we get here we're not allowed to use Bluetooth right now return false; } private Uri creatFileForSharedContent(Context context, CharSequence shareContent) { if (shareContent == null) { return null; } Uri fileUri = null; FileOutputStream outStream = null; try { String fileName = getString(R.string.bluetooth_share_file_name) + ".html"; context.deleteFile(fileName); String uri = shareContent.toString(); String content = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;" + " charset=UTF-8\"/></head><body>" + "<a href=\"" + uri + "\">" + uri + "</a></p>" + "</body></html>"; byte[] byteBuff = content.getBytes(); outStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); if (outStream != null) { outStream.write(byteBuff, 0, byteBuff.length); fileUri = Uri.fromFile(new File(context.getFilesDir(), fileName)); if (fileUri != null) { if (D) Log.d(TAG, "Created one file for shared content: " + fileUri.toString()); } } } catch (FileNotFoundException e) { Log.e(TAG, "FileNotFoundException: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "IOException: " + e.toString()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.toString()); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return fileUri; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String action = intent.getAction(); BluetoothDevice device = null; boolean isHandover = true; if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) { /* * Other application is trying to share a file via Bluetooth, * probably Pictures, videos, or vCards. The Intent should contain * an EXTRA_STREAM with the data to attach. */ if (intent.getBooleanExtra(Constants.EXTRA_CONNECTION_HANDOVER, false)) { device = (BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); isHandover = true; } if (action.equals(Intent.ACTION_SEND)) { // TODO: handle type == null case String type = intent.getType(); Uri stream = (Uri)intent.getParcelableExtra(Intent.EXTRA_STREAM); CharSequence extra_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // If we get ACTION_SEND intent with EXTRA_STREAM, we'll use the // uri data; // If we get ACTION_SEND intent without EXTRA_STREAM, but with // EXTRA_TEXT, we will try send this TEXT out; Currently in // Browser, share one link goes to this case; if (stream != null && type != null) { if (V) Log.v(TAG, "Get ACTION_SEND intent: Uri = " + stream + "; mimetype = " + type); // Save type/stream, will be used when adding transfer // session to DB. BluetoothOppManager.getInstance(this).saveSendingFileInfo(type, stream.toString(), isHandover); } else if (extra_text != null && type != null) { if (V) Log.v(TAG, "Get ACTION_SEND intent with Extra_text = " + extra_text.toString() + "; mimetype = " + type); Uri fileUri = creatFileForSharedContent(this, extra_text); if (fileUri != null) { BluetoothOppManager.getInstance(this).saveSendingFileInfo(type, fileUri.toString(), isHandover); } } else { Log.e(TAG, "type is null; or sending file URI is null"); finish(); return; } } else if (action.equals(Intent.ACTION_SEND_MULTIPLE)) { ArrayList<Uri> uris = new ArrayList<Uri>(); String mimeType = intent.getType(); uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (mimeType != null && uris != null) { if (V) Log.v(TAG, "Get ACTION_SHARE_MULTIPLE intent: uris " + uris + "\n Type= " + mimeType); BluetoothOppManager.getInstance(this).saveSendingFileInfo(mimeType, uris, isHandover); } else { Log.e(TAG, "type is null; or sending files URIs are null"); finish(); return; } } if (!isBluetoothAllowed()) { Intent in = new Intent(this, BluetoothOppBtErrorActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); in.putExtra("title", this.getString(R.string.airplane_error_title)); in.putExtra("content", this.getString(R.string.airplane_error_msg)); this.startActivity(in); finish(); return; } // TODO: In the future, we may send intent to DevicePickerActivity // directly, // and let DevicePickerActivity to handle Bluetooth Enable. if (!BluetoothOppManager.getInstance(this).isEnabled()) { if (V) Log.v(TAG, "Prepare Enable BT!! "); Intent in = new Intent(this, BluetoothOppBtEnableActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(in); } else if (device == null) { if (V) Log.v(TAG, "BT already enabled!! "); Intent in1 = new Intent(BluetoothDevicePicker.ACTION_LAUNCH); in1.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); in1.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false); in1.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE, BluetoothDevicePicker.FILTER_TYPE_TRANSFER); in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_PACKAGE, Constants.THIS_PACKAGE_NAME); in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_CLASS, BluetoothOppReceiver.class.getName()); this.startActivity(in1); } else { // we already know where to send to BluetoothOppManager.getInstance(this).startTransfer(device); } } else if (action.equals(Constants.ACTION_OPEN)) { Uri uri = getIntent().getData(); if (V) Log.v(TAG, "Get ACTION_OPEN intent: Uri = " + uri); Intent intent1 = new Intent(); intent1.setAction(action); intent1.setClassName(Constants.THIS_PACKAGE_NAME, BluetoothOppReceiver.class.getName()); intent1.setData(uri); this.sendBroadcast(intent1); } finish(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String action = intent.getAction(); BluetoothDevice device = null; boolean isHandover = false; if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) { /* * Other application is trying to share a file via Bluetooth, * probably Pictures, videos, or vCards. The Intent should contain * an EXTRA_STREAM with the data to attach. */ if (intent.getBooleanExtra(Constants.EXTRA_CONNECTION_HANDOVER, false)) { device = (BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); isHandover = true; } if (action.equals(Intent.ACTION_SEND)) { // TODO: handle type == null case String type = intent.getType(); Uri stream = (Uri)intent.getParcelableExtra(Intent.EXTRA_STREAM); CharSequence extra_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // If we get ACTION_SEND intent with EXTRA_STREAM, we'll use the // uri data; // If we get ACTION_SEND intent without EXTRA_STREAM, but with // EXTRA_TEXT, we will try send this TEXT out; Currently in // Browser, share one link goes to this case; if (stream != null && type != null) { if (V) Log.v(TAG, "Get ACTION_SEND intent: Uri = " + stream + "; mimetype = " + type); // Save type/stream, will be used when adding transfer // session to DB. BluetoothOppManager.getInstance(this).saveSendingFileInfo(type, stream.toString(), isHandover); } else if (extra_text != null && type != null) { if (V) Log.v(TAG, "Get ACTION_SEND intent with Extra_text = " + extra_text.toString() + "; mimetype = " + type); Uri fileUri = creatFileForSharedContent(this, extra_text); if (fileUri != null) { BluetoothOppManager.getInstance(this).saveSendingFileInfo(type, fileUri.toString(), isHandover); } } else { Log.e(TAG, "type is null; or sending file URI is null"); finish(); return; } } else if (action.equals(Intent.ACTION_SEND_MULTIPLE)) { ArrayList<Uri> uris = new ArrayList<Uri>(); String mimeType = intent.getType(); uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (mimeType != null && uris != null) { if (V) Log.v(TAG, "Get ACTION_SHARE_MULTIPLE intent: uris " + uris + "\n Type= " + mimeType); BluetoothOppManager.getInstance(this).saveSendingFileInfo(mimeType, uris, isHandover); } else { Log.e(TAG, "type is null; or sending files URIs are null"); finish(); return; } } if (!isBluetoothAllowed()) { Intent in = new Intent(this, BluetoothOppBtErrorActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); in.putExtra("title", this.getString(R.string.airplane_error_title)); in.putExtra("content", this.getString(R.string.airplane_error_msg)); this.startActivity(in); finish(); return; } // TODO: In the future, we may send intent to DevicePickerActivity // directly, // and let DevicePickerActivity to handle Bluetooth Enable. if (!BluetoothOppManager.getInstance(this).isEnabled()) { if (V) Log.v(TAG, "Prepare Enable BT!! "); Intent in = new Intent(this, BluetoothOppBtEnableActivity.class); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(in); } else if (device == null) { if (V) Log.v(TAG, "BT already enabled!! "); Intent in1 = new Intent(BluetoothDevicePicker.ACTION_LAUNCH); in1.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); in1.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false); in1.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE, BluetoothDevicePicker.FILTER_TYPE_TRANSFER); in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_PACKAGE, Constants.THIS_PACKAGE_NAME); in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_CLASS, BluetoothOppReceiver.class.getName()); this.startActivity(in1); } else { // we already know where to send to BluetoothOppManager.getInstance(this).startTransfer(device); } } else if (action.equals(Constants.ACTION_OPEN)) { Uri uri = getIntent().getData(); if (V) Log.v(TAG, "Get ACTION_OPEN intent: Uri = " + uri); Intent intent1 = new Intent(); intent1.setAction(action); intent1.setClassName(Constants.THIS_PACKAGE_NAME, BluetoothOppReceiver.class.getName()); intent1.setData(uri); this.sendBroadcast(intent1); } finish(); }
diff --git a/pingpongnet/src/test/java/ping/pong/net/connection/io/ReadFullyDataReaderTest.java b/pingpongnet/src/test/java/ping/pong/net/connection/io/ReadFullyDataReaderTest.java index 3f6490d..a6b639a 100644 --- a/pingpongnet/src/test/java/ping/pong/net/connection/io/ReadFullyDataReaderTest.java +++ b/pingpongnet/src/test/java/ping/pong/net/connection/io/ReadFullyDataReaderTest.java @@ -1,124 +1,124 @@ package ping.pong.net.connection.io; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.*; /** * * @author mfullen */ public class ReadFullyDataReaderTest { private static final Logger LOGGER = LoggerFactory.getLogger(ReadFullyDataReaderTest.class); public ReadFullyDataReaderTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of init method, of class ReadFullyDataReader. */ @Test public void testReadFullyDataReader() throws IOException, InterruptedException { Runnable serverSocket = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(10121); Socket acceptingSocket = serverSocket.accept(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(acceptingSocket.getOutputStream()); for (int i = 0; i < 10; i++) { String messageString = "Test" + i; LOGGER.debug("Message byte[] size: " + messageString.getBytes().length); byte[] size = ByteBuffer.allocate(4).putInt(messageString.getBytes().length).array(); byte[] message = messageString.getBytes(); bufferedOutputStream.write(size); bufferedOutputStream.write(message); bufferedOutputStream.flush(); } } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread serverThread = new Thread(serverSocket); serverThread.start(); final String[] results = new String[10]; Runnable reader = new Runnable() { boolean running = true; @Override public void run() { try { ReadFullyDataReader readFullyDataReader = new ReadFullyDataReader(); readFullyDataReader.init(SocketFactory.getDefault().createSocket("localhost", 10121)); int i = 0; - while (running) + while (i <= 9) { byte[] readData = readFullyDataReader.readData(); LOGGER.debug("ReadData: " + readData); results[i] = new String(readData); i++; } } catch (UnknownHostException ex) { LOGGER.error("Error", ex); } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread readerThread = new Thread(reader); readerThread.start(); - serverThread.join(100); - readerThread.join(150); + serverThread.join(); + readerThread.join(); int i = 0; for (int j = 0; j < results.length; j++, i++) { String result = results[j]; String expected = "Test" + i; assertEquals(expected, result); } } }
false
true
public void testReadFullyDataReader() throws IOException, InterruptedException { Runnable serverSocket = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(10121); Socket acceptingSocket = serverSocket.accept(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(acceptingSocket.getOutputStream()); for (int i = 0; i < 10; i++) { String messageString = "Test" + i; LOGGER.debug("Message byte[] size: " + messageString.getBytes().length); byte[] size = ByteBuffer.allocate(4).putInt(messageString.getBytes().length).array(); byte[] message = messageString.getBytes(); bufferedOutputStream.write(size); bufferedOutputStream.write(message); bufferedOutputStream.flush(); } } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread serverThread = new Thread(serverSocket); serverThread.start(); final String[] results = new String[10]; Runnable reader = new Runnable() { boolean running = true; @Override public void run() { try { ReadFullyDataReader readFullyDataReader = new ReadFullyDataReader(); readFullyDataReader.init(SocketFactory.getDefault().createSocket("localhost", 10121)); int i = 0; while (running) { byte[] readData = readFullyDataReader.readData(); LOGGER.debug("ReadData: " + readData); results[i] = new String(readData); i++; } } catch (UnknownHostException ex) { LOGGER.error("Error", ex); } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread readerThread = new Thread(reader); readerThread.start(); serverThread.join(100); readerThread.join(150); int i = 0; for (int j = 0; j < results.length; j++, i++) { String result = results[j]; String expected = "Test" + i; assertEquals(expected, result); } }
public void testReadFullyDataReader() throws IOException, InterruptedException { Runnable serverSocket = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(10121); Socket acceptingSocket = serverSocket.accept(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(acceptingSocket.getOutputStream()); for (int i = 0; i < 10; i++) { String messageString = "Test" + i; LOGGER.debug("Message byte[] size: " + messageString.getBytes().length); byte[] size = ByteBuffer.allocate(4).putInt(messageString.getBytes().length).array(); byte[] message = messageString.getBytes(); bufferedOutputStream.write(size); bufferedOutputStream.write(message); bufferedOutputStream.flush(); } } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread serverThread = new Thread(serverSocket); serverThread.start(); final String[] results = new String[10]; Runnable reader = new Runnable() { boolean running = true; @Override public void run() { try { ReadFullyDataReader readFullyDataReader = new ReadFullyDataReader(); readFullyDataReader.init(SocketFactory.getDefault().createSocket("localhost", 10121)); int i = 0; while (i <= 9) { byte[] readData = readFullyDataReader.readData(); LOGGER.debug("ReadData: " + readData); results[i] = new String(readData); i++; } } catch (UnknownHostException ex) { LOGGER.error("Error", ex); } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread readerThread = new Thread(reader); readerThread.start(); serverThread.join(); readerThread.join(); int i = 0; for (int j = 0; j < results.length; j++, i++) { String result = results[j]; String expected = "Test" + i; assertEquals(expected, result); } }
diff --git a/rdflivenews-core/src/main/java/org/aksw/simba/rdflivenews/rdf/impl/NIFRdfExtraction.java b/rdflivenews-core/src/main/java/org/aksw/simba/rdflivenews/rdf/impl/NIFRdfExtraction.java index 2c0c3c4..a198086 100644 --- a/rdflivenews-core/src/main/java/org/aksw/simba/rdflivenews/rdf/impl/NIFRdfExtraction.java +++ b/rdflivenews-core/src/main/java/org/aksw/simba/rdflivenews/rdf/impl/NIFRdfExtraction.java @@ -1,395 +1,396 @@ /** * */ package org.aksw.simba.rdflivenews.rdf.impl; import com.github.gerbsen.rdf.JenaUtil; import com.hp.hpl.jena.datatypes.xsd.XSDDateTime; import com.hp.hpl.jena.ontology.*; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.FileManager; import com.hp.hpl.jena.vocabulary.DCTerms; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import org.aksw.simba.rdflivenews.RdfLiveNews; import org.aksw.simba.rdflivenews.cluster.Cluster; import org.aksw.simba.rdflivenews.index.Extraction; import org.aksw.simba.rdflivenews.index.IndexManager; import org.aksw.simba.rdflivenews.pair.EntityPair; import org.aksw.simba.rdflivenews.pattern.Pattern; import org.aksw.simba.rdflivenews.rdf.RdfExtraction; import org.aksw.simba.rdflivenews.rdf.triple.Triple; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.HiddenFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import java.io.*; import java.net.URLEncoder; import java.security.NoSuchAlgorithmException; import java.util.*; /** * @author Sebastian Hellmann <[email protected]> */ public class NIFRdfExtraction implements RdfExtraction { private Logger logger = Logger.getLogger(getClass()); public static final String BASE = "http://rdflivenews.aksw.org/extraction/"; public final String data_dir; public final String output_file; public boolean testing = false; public Map<String, OntModel> source2ModelMap = new HashMap<String, OntModel>(); private static Map<String, String> prefixes = new HashMap<String, String>(); Set<String> tokens = new HashSet<String>(Arrays.asList("asked", "reported", "said", "said that", ", '' said", "tells", "noted that", "told", "said of", "said in", "calls", "said ,", "announced", ", told", ", '' says", ", said", "called", "says", "says that", "said on")); public NIFRdfExtraction() { output_file = (RdfLiveNews.DATA_DIRECTORY != null) ? RdfLiveNews.DATA_DIRECTORY + "rdf/normal.ttl" : "normal.ttl"; data_dir = (RdfLiveNews.DATA_DIRECTORY != null) ? RdfLiveNews.DATA_DIRECTORY + "rdf/" : "results/"; } public static int errorCount = 0; public static int totalPairs = 0; private boolean isSayClusterPattern(Pattern pattern) { return tokens.contains(pattern.getNaturalLanguageRepresentation()); } @Override public List<Triple> extractRdf(Set<Cluster<Pattern>> clusters) { List<Triple> triples = new ArrayList<Triple>(); for (Cluster<Pattern> cluster : clusters) { for (Pattern pattern : cluster) { if (!isSayClusterPattern(pattern)) { for (EntityPair pair : pattern.getLearnedFromEntities()) { totalPairs++; try { extractRdfFromEntityPair(pair, cluster, pattern); } catch (Exception e) { logger.error("An error (" + (++errorCount) + " of " + totalPairs + ") occurred, continuing", e); System.out.println("An error (" + (++errorCount) + " of " + totalPairs + ") occurred, continuing"); } } } } } OntModel total = ModelFactory.createOntologyModel(); setPrefixes(total); for (String sourceUrlNoHttp : source2ModelMap.keySet()) { OntModel m = source2ModelMap.get(sourceUrlNoHttp); total.add(m); String path = new File(data_dir + sourceUrlNoHttp).getParent(); String name = new File(data_dir + sourceUrlNoHttp).getName(); try { File f = new File(path + "/" + URLEncoder.encode(name, "UTF-8")); if (f.getParent() != null) { new File(f.getParent()).mkdirs(); } m.write(new FileWriter(f), "N3"); } catch (IOException ioe) { logger.error("couldn't write to " + path + "/" + name, ioe); } } try { total.write(new FileWriter(output_file), "N3"); StringWriter sw = new StringWriter(); total.write(sw, "N3"); if (testing) System.out.println(sw.toString()); } catch (IOException ioe) { logger.error("couldn't write to " + output_file, ioe); } return triples; } public void extractRdfFromEntityPair(EntityPair pair, Cluster<Pattern> cluster, Pattern pattern) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (!pair.hasValidUris()) { logger.debug("NON VALID URIS: \n" + pair); return; } if (testing || check(pair, cluster, pattern)) { Set<Extraction> extractions = new HashSet<Extraction>(); if (testing) { String url = "http://www.usatoday.com/money/industries/energy/environment/2010-02-03-windpower_N.htm?test=ee&aa=bb"; String text = "... costs of the Wi-Fi system , '' explains Houston Airports spokesperson Marlene McClinton , `` And charges ..."; String date = "1307916000000"; extractions.add(new Extraction(url, text, date)); } else { extractions = IndexManager.getInstance().getTextArticleDateAndArticleUrl(pair.getLuceneSentenceIds()); } // extraction for (Extraction extraction : extractions) { //get basic info String sourceUrl = extraction.url; if (sourceUrl.contains("#")) { logger.info("contains #: " + sourceUrl); sourceUrl = sourceUrl.substring(0, sourceUrl.indexOf('#')); } String date = extraction.date; String sentence = extraction.text; String normSent = (sentence.length() > 200) ? sentence.substring(0, 200) : sentence; normSent = DigestUtils.md5Hex(sentence); - String sourceUrlNoHttpWithSentence = sourceUrl.substring("http://".length()) + "/" + URLEncoder.encode(normSent, "UTF-8"); + String sourceUrlNoHttpWithSentence = sourceUrl.substring("http://".length()) + "/" + normSent; + //String sourceUrlNoHttpWithSentence = sourceUrl.substring("http://".length()) + "/" + URLEncoder.encode(normSent, "UTF-8"); logger.info(sentence); logger.info(sourceUrl); logger.info(date); //make a model OntModel model = ModelFactory.createOntologyModel(); setPrefixes(model); logger.info(cluster.getRdfsDomain()); logger.info(cluster.getRdfsRange()); OntClass subjectClass = model.createClass((cluster.getRdfsDomain() == null) ? OWL.Thing.toString() : cluster.getRdfsDomain()); OntClass objectClass = model.createClass((cluster.getRdfsDomain() == null) ? OWL.Thing.toString() : cluster.getRdfsDomain()); logger.info(pair.getFirstEntity().toString()); logger.info(pair.getSecondEntity().toString()); Individual subject = model.createIndividual(pair.getFirstEntity().getUri(), subjectClass); Individual object = model.createIndividual(pair.getSecondEntity().getUri(), objectClass); ObjectProperty op = model.createObjectProperty(cluster.getUri()); //assign refined labels if possible subject.setLabel((pair.getFirstEntity().getRefinedLabel() == null || pair.getFirstEntity().getRefinedLabel().isEmpty()) ? pair.getFirstEntity().getLabel() : pair.getFirstEntity().getRefinedLabel(), "en"); object.setLabel((pair.getSecondEntity().getRefinedLabel() == null || pair.getSecondEntity().getRefinedLabel().isEmpty()) ? pair.getSecondEntity().getLabel() : pair.getSecondEntity().getRefinedLabel(), "en"); //add the connection between subject and object subject.addProperty(op, object); //use it as the context URI String prefix = BASE + sourceUrlNoHttpWithSentence + "#"; //context Individual context = model.createIndividual(prefix + "char=0,", NIFOntClasses.RFC5147String.getOntClass(model)); context.addOntClass(NIFOntClasses.Context.getOntClass(model)); context.addOntClass(NIFOntClasses.String.getOntClass(model)); context.addProperty(NIFObjectProperties.referenceContext.getObjectProperty(model), context); context.addProperty(NIFDatatypeProperties.isString.getDatatypeProperty(model), sentence); Individual sourceUrlIndividual = model.createIndividual(sourceUrl, OWL.Thing); context.addProperty(NIFObjectProperties.sourceUrl.getObjectProperty(model), sourceUrlIndividual); /******************************************************************* * Finally, we succeed in creating ISO conform dateTime strings! *******************************************************************/ DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis(); XSDDateTime now = new XSDDateTime(Calendar.getInstance()); try { sourceUrlIndividual.addProperty(DCTerms.created, formatter.print(new Long(date).longValue()), now.getNarrowedDatatype()); } catch (Exception exception) { logger.debug("date parsing not working: " + date, exception); } DateTime dt = new DateTime(); context.addProperty(DCTerms.created, dt.toString(formatter), now.getNarrowedDatatype()); //prepare the sentence: String propertySurfaceForm = pattern.getNaturalLanguageRepresentation(); int propertyBeginIndex = sentence.indexOf(propertySurfaceForm); int propertyEndIndex = propertyBeginIndex + pattern.getNaturalLanguageRepresentation().length(); Individual propertyNIFString = assignURI(prefix, propertySurfaceForm, context, model, propertyBeginIndex, propertyEndIndex); //generate URI for the object and subject int bi = sentence.substring(0, propertyBeginIndex).lastIndexOf(pair.getFirstEntity().getLabel()); int ei = bi + pair.getFirstEntity().getLabel().length(); Individual subjectNIFString = assignURI(prefix, pair.getFirstEntity().getLabel(), context, model, bi, ei); bi = sentence.substring(propertyBeginIndex).indexOf(pair.getSecondEntity().getLabel()); ei = bi + pair.getSecondEntity().getLabel().length(); Individual objectNIFString = assignURI(prefix, pair.getSecondEntity().getLabel(), context, model, bi, ei); // connect them String itsrdfns = "http://www.w3.org/2005/11/its/rdf#"; ObjectProperty taIdentRef = model.createObjectProperty(itsrdfns + "taIdentRef"); AnnotationProperty taClassRef = model.createAnnotationProperty(itsrdfns + "taClassRef"); AnnotationProperty taPropRef = model.createAnnotationProperty(itsrdfns + "taPropRef"); subjectNIFString.addProperty(taIdentRef, subject); subjectNIFString.addProperty(taClassRef, subjectClass); objectNIFString.addProperty(taIdentRef, object); objectNIFString.addProperty(taClassRef, objectClass); propertyNIFString.addProperty(taPropRef, op); - if (source2ModelMap.containsKey(sourceUrl)) { + if (source2ModelMap.containsKey(sourceUrlNoHttpWithSentence)) { source2ModelMap.get(sourceUrlNoHttpWithSentence).add(model); } else { source2ModelMap.put(sourceUrlNoHttpWithSentence, model); } } } } /* public static int doubletteCounter = 0; public static int totalUriCounter = 0; public static int notFoundCounter = 0; private Individual assignURItoString(String text, String prefix, String surfaceform, Individual context, OntModel m) { if (text.split(surfaceform).length > 2) { logger.error("several occurrence within the same text, happened " + (++doubletteCounter) + " times already: " + context.getURI()); } else if (!text.contains(surfaceform)) { logger.error("no occurrence within the text, happened " + (++notFoundCounter) + " times already: " + context.getURI()); } logger.info("Total: " + (++totalUriCounter) + " notfound: " + notFoundCounter + " doublettes: " + doubletteCounter); int beginIndex = text.indexOf(surfaceform); int endIndex = beginIndex + surfaceform.length(); return assignURI(prefix, surfaceform, context, m, beginIndex, endIndex); } */ private Individual assignURI(String prefix, String surfaceform, Individual context, OntModel m, int beginIndex, int endIndex) { Individual retval = m.createIndividual(prefix + "char=" + beginIndex + "," + endIndex, NIFOntClasses.RFC5147String.getOntClass(m)); retval.addOntClass(NIFOntClasses.String.getOntClass(m)); retval.addProperty(NIFObjectProperties.referenceContext.getObjectProperty(m), context); retval.addLiteral(NIFDatatypeProperties.anchorOf.getDatatypeProperty(m), surfaceform); retval.addLiteral(NIFDatatypeProperties.beginIndex.getDatatypeProperty(m), beginIndex); retval.addLiteral(NIFDatatypeProperties.endIndex.getDatatypeProperty(m), endIndex); return retval; } private void setPrefixes(OntModel model) { model.setNsPrefix("rdf", RDF.getURI()); model.setNsPrefix("owl", OWL.getURI()); model.setNsPrefix("dbpedia", "http://dbpedia.org/resource/"); model.setNsPrefix("dbo", "http://dbpedia.org/ontology/"); model.setNsPrefix("rln-ont", "http://rdflivenews.aksw.org/ontology/"); model.setNsPrefix("rln-res", "http://rdflivenews.aksw.org/resource/"); model.setNsPrefix("itsrdf", "http://www.w3.org/2005/11/its/rdf#"); NIFNamespaces.addNifPrefix(model); } private boolean check(EntityPair pair, Cluster<Pattern> cluster, Pattern pattern) { if (testing) { return true; } boolean check = false; //enable option check = (RdfLiveNews.CONFIG.getBooleanSetting("extraction", "enforceCorrectTypes")) ? check : true; //if enabled do the check check = (check || pair.getFirstEntity().getType() .equals(cluster.getRdfsDomain()) && pair.getSecondEntity().getType() .equals(cluster.getRdfsRange())); if (!check) { logger.error("WRONG D/R: " + pattern.getNaturalLanguageRepresentationWithTags()); } return check; } // @Override // public void uploadRdf() { // // try { // // String graph = RdfLiveNews.CONFIG.getStringSetting("sparql", "graph"); // String server = RdfLiveNews.CONFIG.getStringSetting("sparql", "uploadServer"); // String username = RdfLiveNews.CONFIG.getStringSetting("sparql", "username"); // String password = RdfLiveNews.CONFIG.getStringSetting("sparql", "password"); // // System.out.println("Server" + server); // // VirtGraph remoteGraph = new VirtGraph(graph, server.replace("charset=UTF-8", ""), username, password); // // Model m = ModelFactory.createMemModelMaker().createDefaultModel(); // m.read(new FileInputStream(new File(RdfLiveNews.DATA_DIRECTORY + "rdf/normal.ttl")),"","N3"); // // StmtIterator iter = m.listStatements(); // // while (iter.hasNext()) { // // com.hp.hpl.jena.graph.Triple t = iter.next().asTriple(); // remoteGraph.add(t); // } // remoteGraph.close(); // } // catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } @Override public void uploadRdf() { RepositoryConnection con = null; try { String graph = RdfLiveNews.CONFIG.getStringSetting("sparql", "graph"); String server = RdfLiveNews.CONFIG.getStringSetting("sparql", "uploadServer"); String username = RdfLiveNews.CONFIG.getStringSetting("sparql", "username"); String password = RdfLiveNews.CONFIG.getStringSetting("sparql", "password"); Repository myRepository = new virtuoso.sesame2.driver.VirtuosoRepository(server,username,password); myRepository.initialize(); // Repository repository = new VirtuosoRepository(server, username, password); con = myRepository.getConnection(); // con = repository.getConnection(); con.add(new File(RdfLiveNews.DATA_DIRECTORY + "rdf/normal.ttl"), graph, RDFFormat.TURTLE); con.close(); } catch (RepositoryException | RDFParseException | IOException e) { e.printStackTrace(); } } public static void main(String[] args) { RdfLiveNews.init(); NIFRdfExtraction ex = new NIFRdfExtraction(); ex.uploadRdf(); } }
false
true
public void extractRdfFromEntityPair(EntityPair pair, Cluster<Pattern> cluster, Pattern pattern) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (!pair.hasValidUris()) { logger.debug("NON VALID URIS: \n" + pair); return; } if (testing || check(pair, cluster, pattern)) { Set<Extraction> extractions = new HashSet<Extraction>(); if (testing) { String url = "http://www.usatoday.com/money/industries/energy/environment/2010-02-03-windpower_N.htm?test=ee&aa=bb"; String text = "... costs of the Wi-Fi system , '' explains Houston Airports spokesperson Marlene McClinton , `` And charges ..."; String date = "1307916000000"; extractions.add(new Extraction(url, text, date)); } else { extractions = IndexManager.getInstance().getTextArticleDateAndArticleUrl(pair.getLuceneSentenceIds()); } // extraction for (Extraction extraction : extractions) { //get basic info String sourceUrl = extraction.url; if (sourceUrl.contains("#")) { logger.info("contains #: " + sourceUrl); sourceUrl = sourceUrl.substring(0, sourceUrl.indexOf('#')); } String date = extraction.date; String sentence = extraction.text; String normSent = (sentence.length() > 200) ? sentence.substring(0, 200) : sentence; normSent = DigestUtils.md5Hex(sentence); String sourceUrlNoHttpWithSentence = sourceUrl.substring("http://".length()) + "/" + URLEncoder.encode(normSent, "UTF-8"); logger.info(sentence); logger.info(sourceUrl); logger.info(date); //make a model OntModel model = ModelFactory.createOntologyModel(); setPrefixes(model); logger.info(cluster.getRdfsDomain()); logger.info(cluster.getRdfsRange()); OntClass subjectClass = model.createClass((cluster.getRdfsDomain() == null) ? OWL.Thing.toString() : cluster.getRdfsDomain()); OntClass objectClass = model.createClass((cluster.getRdfsDomain() == null) ? OWL.Thing.toString() : cluster.getRdfsDomain()); logger.info(pair.getFirstEntity().toString()); logger.info(pair.getSecondEntity().toString()); Individual subject = model.createIndividual(pair.getFirstEntity().getUri(), subjectClass); Individual object = model.createIndividual(pair.getSecondEntity().getUri(), objectClass); ObjectProperty op = model.createObjectProperty(cluster.getUri()); //assign refined labels if possible subject.setLabel((pair.getFirstEntity().getRefinedLabel() == null || pair.getFirstEntity().getRefinedLabel().isEmpty()) ? pair.getFirstEntity().getLabel() : pair.getFirstEntity().getRefinedLabel(), "en"); object.setLabel((pair.getSecondEntity().getRefinedLabel() == null || pair.getSecondEntity().getRefinedLabel().isEmpty()) ? pair.getSecondEntity().getLabel() : pair.getSecondEntity().getRefinedLabel(), "en"); //add the connection between subject and object subject.addProperty(op, object); //use it as the context URI String prefix = BASE + sourceUrlNoHttpWithSentence + "#"; //context Individual context = model.createIndividual(prefix + "char=0,", NIFOntClasses.RFC5147String.getOntClass(model)); context.addOntClass(NIFOntClasses.Context.getOntClass(model)); context.addOntClass(NIFOntClasses.String.getOntClass(model)); context.addProperty(NIFObjectProperties.referenceContext.getObjectProperty(model), context); context.addProperty(NIFDatatypeProperties.isString.getDatatypeProperty(model), sentence); Individual sourceUrlIndividual = model.createIndividual(sourceUrl, OWL.Thing); context.addProperty(NIFObjectProperties.sourceUrl.getObjectProperty(model), sourceUrlIndividual); /******************************************************************* * Finally, we succeed in creating ISO conform dateTime strings! *******************************************************************/ DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis(); XSDDateTime now = new XSDDateTime(Calendar.getInstance()); try { sourceUrlIndividual.addProperty(DCTerms.created, formatter.print(new Long(date).longValue()), now.getNarrowedDatatype()); } catch (Exception exception) { logger.debug("date parsing not working: " + date, exception); } DateTime dt = new DateTime(); context.addProperty(DCTerms.created, dt.toString(formatter), now.getNarrowedDatatype()); //prepare the sentence: String propertySurfaceForm = pattern.getNaturalLanguageRepresentation(); int propertyBeginIndex = sentence.indexOf(propertySurfaceForm); int propertyEndIndex = propertyBeginIndex + pattern.getNaturalLanguageRepresentation().length(); Individual propertyNIFString = assignURI(prefix, propertySurfaceForm, context, model, propertyBeginIndex, propertyEndIndex); //generate URI for the object and subject int bi = sentence.substring(0, propertyBeginIndex).lastIndexOf(pair.getFirstEntity().getLabel()); int ei = bi + pair.getFirstEntity().getLabel().length(); Individual subjectNIFString = assignURI(prefix, pair.getFirstEntity().getLabel(), context, model, bi, ei); bi = sentence.substring(propertyBeginIndex).indexOf(pair.getSecondEntity().getLabel()); ei = bi + pair.getSecondEntity().getLabel().length(); Individual objectNIFString = assignURI(prefix, pair.getSecondEntity().getLabel(), context, model, bi, ei); // connect them String itsrdfns = "http://www.w3.org/2005/11/its/rdf#"; ObjectProperty taIdentRef = model.createObjectProperty(itsrdfns + "taIdentRef"); AnnotationProperty taClassRef = model.createAnnotationProperty(itsrdfns + "taClassRef"); AnnotationProperty taPropRef = model.createAnnotationProperty(itsrdfns + "taPropRef"); subjectNIFString.addProperty(taIdentRef, subject); subjectNIFString.addProperty(taClassRef, subjectClass); objectNIFString.addProperty(taIdentRef, object); objectNIFString.addProperty(taClassRef, objectClass); propertyNIFString.addProperty(taPropRef, op); if (source2ModelMap.containsKey(sourceUrl)) { source2ModelMap.get(sourceUrlNoHttpWithSentence).add(model); } else { source2ModelMap.put(sourceUrlNoHttpWithSentence, model); } } } }
public void extractRdfFromEntityPair(EntityPair pair, Cluster<Pattern> cluster, Pattern pattern) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (!pair.hasValidUris()) { logger.debug("NON VALID URIS: \n" + pair); return; } if (testing || check(pair, cluster, pattern)) { Set<Extraction> extractions = new HashSet<Extraction>(); if (testing) { String url = "http://www.usatoday.com/money/industries/energy/environment/2010-02-03-windpower_N.htm?test=ee&aa=bb"; String text = "... costs of the Wi-Fi system , '' explains Houston Airports spokesperson Marlene McClinton , `` And charges ..."; String date = "1307916000000"; extractions.add(new Extraction(url, text, date)); } else { extractions = IndexManager.getInstance().getTextArticleDateAndArticleUrl(pair.getLuceneSentenceIds()); } // extraction for (Extraction extraction : extractions) { //get basic info String sourceUrl = extraction.url; if (sourceUrl.contains("#")) { logger.info("contains #: " + sourceUrl); sourceUrl = sourceUrl.substring(0, sourceUrl.indexOf('#')); } String date = extraction.date; String sentence = extraction.text; String normSent = (sentence.length() > 200) ? sentence.substring(0, 200) : sentence; normSent = DigestUtils.md5Hex(sentence); String sourceUrlNoHttpWithSentence = sourceUrl.substring("http://".length()) + "/" + normSent; //String sourceUrlNoHttpWithSentence = sourceUrl.substring("http://".length()) + "/" + URLEncoder.encode(normSent, "UTF-8"); logger.info(sentence); logger.info(sourceUrl); logger.info(date); //make a model OntModel model = ModelFactory.createOntologyModel(); setPrefixes(model); logger.info(cluster.getRdfsDomain()); logger.info(cluster.getRdfsRange()); OntClass subjectClass = model.createClass((cluster.getRdfsDomain() == null) ? OWL.Thing.toString() : cluster.getRdfsDomain()); OntClass objectClass = model.createClass((cluster.getRdfsDomain() == null) ? OWL.Thing.toString() : cluster.getRdfsDomain()); logger.info(pair.getFirstEntity().toString()); logger.info(pair.getSecondEntity().toString()); Individual subject = model.createIndividual(pair.getFirstEntity().getUri(), subjectClass); Individual object = model.createIndividual(pair.getSecondEntity().getUri(), objectClass); ObjectProperty op = model.createObjectProperty(cluster.getUri()); //assign refined labels if possible subject.setLabel((pair.getFirstEntity().getRefinedLabel() == null || pair.getFirstEntity().getRefinedLabel().isEmpty()) ? pair.getFirstEntity().getLabel() : pair.getFirstEntity().getRefinedLabel(), "en"); object.setLabel((pair.getSecondEntity().getRefinedLabel() == null || pair.getSecondEntity().getRefinedLabel().isEmpty()) ? pair.getSecondEntity().getLabel() : pair.getSecondEntity().getRefinedLabel(), "en"); //add the connection between subject and object subject.addProperty(op, object); //use it as the context URI String prefix = BASE + sourceUrlNoHttpWithSentence + "#"; //context Individual context = model.createIndividual(prefix + "char=0,", NIFOntClasses.RFC5147String.getOntClass(model)); context.addOntClass(NIFOntClasses.Context.getOntClass(model)); context.addOntClass(NIFOntClasses.String.getOntClass(model)); context.addProperty(NIFObjectProperties.referenceContext.getObjectProperty(model), context); context.addProperty(NIFDatatypeProperties.isString.getDatatypeProperty(model), sentence); Individual sourceUrlIndividual = model.createIndividual(sourceUrl, OWL.Thing); context.addProperty(NIFObjectProperties.sourceUrl.getObjectProperty(model), sourceUrlIndividual); /******************************************************************* * Finally, we succeed in creating ISO conform dateTime strings! *******************************************************************/ DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis(); XSDDateTime now = new XSDDateTime(Calendar.getInstance()); try { sourceUrlIndividual.addProperty(DCTerms.created, formatter.print(new Long(date).longValue()), now.getNarrowedDatatype()); } catch (Exception exception) { logger.debug("date parsing not working: " + date, exception); } DateTime dt = new DateTime(); context.addProperty(DCTerms.created, dt.toString(formatter), now.getNarrowedDatatype()); //prepare the sentence: String propertySurfaceForm = pattern.getNaturalLanguageRepresentation(); int propertyBeginIndex = sentence.indexOf(propertySurfaceForm); int propertyEndIndex = propertyBeginIndex + pattern.getNaturalLanguageRepresentation().length(); Individual propertyNIFString = assignURI(prefix, propertySurfaceForm, context, model, propertyBeginIndex, propertyEndIndex); //generate URI for the object and subject int bi = sentence.substring(0, propertyBeginIndex).lastIndexOf(pair.getFirstEntity().getLabel()); int ei = bi + pair.getFirstEntity().getLabel().length(); Individual subjectNIFString = assignURI(prefix, pair.getFirstEntity().getLabel(), context, model, bi, ei); bi = sentence.substring(propertyBeginIndex).indexOf(pair.getSecondEntity().getLabel()); ei = bi + pair.getSecondEntity().getLabel().length(); Individual objectNIFString = assignURI(prefix, pair.getSecondEntity().getLabel(), context, model, bi, ei); // connect them String itsrdfns = "http://www.w3.org/2005/11/its/rdf#"; ObjectProperty taIdentRef = model.createObjectProperty(itsrdfns + "taIdentRef"); AnnotationProperty taClassRef = model.createAnnotationProperty(itsrdfns + "taClassRef"); AnnotationProperty taPropRef = model.createAnnotationProperty(itsrdfns + "taPropRef"); subjectNIFString.addProperty(taIdentRef, subject); subjectNIFString.addProperty(taClassRef, subjectClass); objectNIFString.addProperty(taIdentRef, object); objectNIFString.addProperty(taClassRef, objectClass); propertyNIFString.addProperty(taPropRef, op); if (source2ModelMap.containsKey(sourceUrlNoHttpWithSentence)) { source2ModelMap.get(sourceUrlNoHttpWithSentence).add(model); } else { source2ModelMap.put(sourceUrlNoHttpWithSentence, model); } } } }
diff --git a/src/main/java/org/mat/nounou/services/ChildrenService.java b/src/main/java/org/mat/nounou/services/ChildrenService.java index 1392c22..5e6db96 100644 --- a/src/main/java/org/mat/nounou/services/ChildrenService.java +++ b/src/main/java/org/mat/nounou/services/ChildrenService.java @@ -1,220 +1,221 @@ package org.mat.nounou.services; import org.mat.nounou.model.Account; import org.mat.nounou.model.Child; import org.mat.nounou.model.Nurse; import org.mat.nounou.servlets.EntityManagerLoaderListener; import org.mat.nounou.util.Constants; import org.mat.nounou.vo.ChildVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; /** * UserVO: mlecoutre * Date: 27/10/12 * Time: 12:01 */ @Path("/children") @Produces(MediaType.APPLICATION_JSON) public class ChildrenService { private static final Logger logger = LoggerFactory.getLogger(ChildrenService.class); @GET @Produces(MediaType.APPLICATION_JSON) public List<ChildVO> get() { logger.debug("Get Child service"); List<Child> kids = null; List<ChildVO> children = new ArrayList<ChildVO>(); EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { TypedQuery<Child> query = em.createQuery("FROM Child", Child.class); query.setMaxResults(Constants.MAX_RESULT); kids = query.getResultList(); } catch (NoResultException nre) { logger.error("No children found in db."); } finally { em.close(); } for (Child c : kids) { ChildVO vo = populate(c); children.add(vo); } return children; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ChildVO registerKid(ChildVO child) { logger.debug("register Child " + child); Child childEntity = new Child(); childEntity.setFirstName(child.getFirstName()); childEntity.setLastName(child.getLastName()); childEntity.setPictureUrl(child.getPictureUrl()); EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { childEntity.setBirthday(Constants.sdfDate.parse(child.getBirthday())); TypedQuery<Account> qAccount = em.createQuery("FROM Account a WHERE accountId=:accountId", Account.class); qAccount.setParameter("accountId", child.getAccountId()); Account account = qAccount.getSingleResult(); childEntity.setAccount(account); TypedQuery<Nurse> qNurse = em.createQuery("FROM Nurse n WHERE nurseId=:nurseId", Nurse.class); qNurse.setParameter("nurseId", child.getNurseId()); Nurse nurse = qNurse.getSingleResult(); childEntity.setNurse(nurse); em.getTransaction().begin(); em.persist(childEntity); em.getTransaction().commit(); child.setChildId(childEntity.getChildId()); child.setNurseName(nurse.getFirstName()); } catch (Exception e) { logger.error("ERROR registerKid", e); } finally { em.close(); } return child; } @POST @Path("/{childId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ChildVO updateChild(ChildVO child, @PathParam("childId") Integer childId) { logger.debug("Update Child " + child); EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { TypedQuery<Child> query = em.createQuery("FROM Child WHERE childId=:childId", Child.class); query.setParameter("childId", childId); Child childEntity = query.getSingleResult(); childEntity.setFirstName(child.getFirstName()); childEntity.setLastName(child.getLastName()); childEntity.setBirthday(Constants.sdfDate.parse(child.getBirthday())); + childEntity.setPictureUrl(child.getPictureUrl); TypedQuery<Account> qAccount = em.createQuery("FROM Account a WHERE accountId=:accountId", Account.class); qAccount.setParameter("accountId", child.getAccountId()); Account account = qAccount.getSingleResult(); childEntity.setAccount(account); TypedQuery<Nurse> qNurse = em.createQuery("FROM Nurse n WHERE nurseId=:nurseId", Nurse.class); qNurse.setParameter("nurseId", child.getNurseId()); Nurse nurse = qNurse.getSingleResult(); childEntity.setNurse(nurse); em.getTransaction().begin(); em.persist(childEntity); em.getTransaction().commit(); child.setChildId(childEntity.getChildId()); child.setNurseName(nurse.getFirstName()); }catch (NoResultException nre){ logger.warn(String.format("No child with childId:%d to update\n", childId)); }catch (Exception e) { logger.error("ERROR in updateChild", e); } finally { em.close(); } return child; } @GET @Path("/account/{accountId}") public List<ChildVO> findByAccountId(@PathParam("accountId") Integer accountId) { List<ChildVO> cList = new ArrayList<ChildVO>(); EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { TypedQuery<Child> query = em.createQuery("FROM Child c WHERE c.account.accountId=:accountId", Child.class); query.setMaxResults(Constants.MAX_RESULT); query.setParameter("accountId", accountId); List<Child> children = query.getResultList(); //populate vo for (Child c : children) { ChildVO vo = populate(c); cList.add(vo); } } catch (NoResultException nre) { logger.warn("No result found for accountId:= " + accountId); } catch (Exception e) { logger.error("ERROR in findByAccountId", e); } finally { em.close(); } return cList; } /** * Populate the value object wihtin the entity * @param c the entity * @return the value object */ public static ChildVO populate(Child c) { ChildVO vo = new ChildVO(); vo.setAccountId(c.getAccount().getAccountId()); if (c.getBirthday() != null) //birthday is an optional parameter vo.setBirthday(Constants.sdfDate.format(c.getBirthday())); vo.setChildId(c.getChildId()); vo.setFirstName(c.getFirstName()); vo.setLastName(c.getLastName()); vo.setPictureUrl(c.getPictureUrl()); if (c.getNurse() != null) { vo.setNurseId(c.getNurse().getNurseId()); vo.setNurseName(c.getNurse().getFirstName().concat(" ").concat(c.getNurse().getLastName())); } return vo; } @GET @Path("/delete/{childId}") public Response deleteById(@PathParam("childId") Integer childId) { EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { em.getTransaction().begin(); TypedQuery<Child> query = em.createQuery(" FROM Child WHERE childId=:childId", Child.class); query.setParameter("childId", childId); Child c = query.getSingleResult(); em.remove(c); em.getTransaction().commit(); } catch (Exception e) { logger.error("ERROR in deleteById", e); return Response.serverError().build(); } finally { em.close(); } return Response.ok().build(); } @GET @Path("/{childId}") public Response getById(@PathParam("childId") Integer childId) { EntityManager em = EntityManagerLoaderListener.createEntityManager(); ChildVO childVO = new ChildVO(); try { TypedQuery<Child> query = em.createQuery("FROM Child WHERE childId=:childId", Child.class); query.setParameter("childId", childId); Child c = query.getSingleResult(); childVO = populate(c); } catch (Exception e) { logger.error("ERROR in getById", e); return Response.serverError().build(); } finally { em.close(); } return Response.ok().entity(childVO).build(); } }
true
true
public ChildVO updateChild(ChildVO child, @PathParam("childId") Integer childId) { logger.debug("Update Child " + child); EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { TypedQuery<Child> query = em.createQuery("FROM Child WHERE childId=:childId", Child.class); query.setParameter("childId", childId); Child childEntity = query.getSingleResult(); childEntity.setFirstName(child.getFirstName()); childEntity.setLastName(child.getLastName()); childEntity.setBirthday(Constants.sdfDate.parse(child.getBirthday())); TypedQuery<Account> qAccount = em.createQuery("FROM Account a WHERE accountId=:accountId", Account.class); qAccount.setParameter("accountId", child.getAccountId()); Account account = qAccount.getSingleResult(); childEntity.setAccount(account); TypedQuery<Nurse> qNurse = em.createQuery("FROM Nurse n WHERE nurseId=:nurseId", Nurse.class); qNurse.setParameter("nurseId", child.getNurseId()); Nurse nurse = qNurse.getSingleResult(); childEntity.setNurse(nurse); em.getTransaction().begin(); em.persist(childEntity); em.getTransaction().commit(); child.setChildId(childEntity.getChildId()); child.setNurseName(nurse.getFirstName()); }catch (NoResultException nre){ logger.warn(String.format("No child with childId:%d to update\n", childId)); }catch (Exception e) { logger.error("ERROR in updateChild", e); } finally { em.close(); } return child; }
public ChildVO updateChild(ChildVO child, @PathParam("childId") Integer childId) { logger.debug("Update Child " + child); EntityManager em = EntityManagerLoaderListener.createEntityManager(); try { TypedQuery<Child> query = em.createQuery("FROM Child WHERE childId=:childId", Child.class); query.setParameter("childId", childId); Child childEntity = query.getSingleResult(); childEntity.setFirstName(child.getFirstName()); childEntity.setLastName(child.getLastName()); childEntity.setBirthday(Constants.sdfDate.parse(child.getBirthday())); childEntity.setPictureUrl(child.getPictureUrl); TypedQuery<Account> qAccount = em.createQuery("FROM Account a WHERE accountId=:accountId", Account.class); qAccount.setParameter("accountId", child.getAccountId()); Account account = qAccount.getSingleResult(); childEntity.setAccount(account); TypedQuery<Nurse> qNurse = em.createQuery("FROM Nurse n WHERE nurseId=:nurseId", Nurse.class); qNurse.setParameter("nurseId", child.getNurseId()); Nurse nurse = qNurse.getSingleResult(); childEntity.setNurse(nurse); em.getTransaction().begin(); em.persist(childEntity); em.getTransaction().commit(); child.setChildId(childEntity.getChildId()); child.setNurseName(nurse.getFirstName()); }catch (NoResultException nre){ logger.warn(String.format("No child with childId:%d to update\n", childId)); }catch (Exception e) { logger.error("ERROR in updateChild", e); } finally { em.close(); } return child; }
diff --git a/core/src/java/com/dtolabs/rundeck/core/common/NodeEntryFactory.java b/core/src/java/com/dtolabs/rundeck/core/common/NodeEntryFactory.java index 57aba34cd..b2a231713 100644 --- a/core/src/java/com/dtolabs/rundeck/core/common/NodeEntryFactory.java +++ b/core/src/java/com/dtolabs/rundeck/core/common/NodeEntryFactory.java @@ -1,119 +1,125 @@ /* * Copyright 2011 DTO Labs, Inc. (http://dtolabs.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * NodeEntryFactory.java * * User: Greg Schueler <a href="mailto:[email protected]">[email protected]</a> * Created: Jan 20, 2011 11:58:42 AM * */ package com.dtolabs.rundeck.core.common; import org.apache.commons.beanutils.BeanUtils; import java.util.*; import java.lang.reflect.InvocationTargetException; import com.dtolabs.shared.resources.ResourceXMLConstants; /** * NodeEntryFactory creates NodeEntryImpls * * @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a> */ public class NodeEntryFactory { /** * Properties to exclude when creating NodeEntryImpl from parsed input data */ private static String[] excludeProps = { "attributes", "frameworkProject", "class" }; /** * Create NodeEntryImpl from map data. It will convert "tags" of type String as a comma separated list of tags, or * "tags" a collection of strings into a set. It will remove properties excluded from allowed import. * * @param map input map data * * @return * * @throws IllegalArgumentException */ @SuppressWarnings ("unchecked") public static NodeEntryImpl createFromMap(final Map<String, Object> map) throws IllegalArgumentException { final NodeEntryImpl nodeEntry = new NodeEntryImpl(); final HashMap<String, Object> newmap = new HashMap<String, Object>(map); for (final String excludeProp : excludeProps) { newmap.remove(excludeProp); } if (null != newmap.get("tags") && newmap.get("tags") instanceof String) { String tags = (String) newmap.get("tags"); String[] data; if ("".equals(tags.trim())) { data = new String[0]; } else { data = tags.split(", *"); } HashSet set = new HashSet(Arrays.asList(data)); newmap.put("tags", set); } else if (null != newmap.get("tags") && newmap.get("tags") instanceof Collection) { Collection tags = (Collection) newmap.get("tags"); - HashSet data = new HashSet(tags); + HashSet data = new HashSet(); + for (final Object tag : tags) { + data.add(tag.toString()); + } newmap.put("tags", data); + }else if (null != newmap.get("tags")) { + Object o = newmap.get("tags"); + newmap.put("tags", new HashSet(Arrays.asList(o.toString()))); } try { BeanUtils.populate(nodeEntry, newmap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (null == nodeEntry.getNodename()) { throw new IllegalArgumentException("Required property 'nodename' was not specified"); } if (null == nodeEntry.getHostname()) { throw new IllegalArgumentException("Required property 'hostname' was not specified"); } if (null == nodeEntry.getAttributes()) { nodeEntry.setAttributes(new HashMap<String, String>()); } //populate attributes with any keys outside of nodeprops for (final Map.Entry<String, Object> entry : newmap.entrySet()) { if (!ResourceXMLConstants.allPropSet.contains(entry.getKey())) { nodeEntry.setAttribute(entry.getKey(), (String) entry.getValue()); } } return nodeEntry; } public static Map<String,String> toMap(final INodeEntry node) { HashMap<String, String> map = new HashMap<String, String>(); if(null!=node.getAttributes()) { map.putAll(node.getAttributes()); } if(null==map.get("tags")) { map.put("tags", ""); } return map; } }
false
true
public static NodeEntryImpl createFromMap(final Map<String, Object> map) throws IllegalArgumentException { final NodeEntryImpl nodeEntry = new NodeEntryImpl(); final HashMap<String, Object> newmap = new HashMap<String, Object>(map); for (final String excludeProp : excludeProps) { newmap.remove(excludeProp); } if (null != newmap.get("tags") && newmap.get("tags") instanceof String) { String tags = (String) newmap.get("tags"); String[] data; if ("".equals(tags.trim())) { data = new String[0]; } else { data = tags.split(", *"); } HashSet set = new HashSet(Arrays.asList(data)); newmap.put("tags", set); } else if (null != newmap.get("tags") && newmap.get("tags") instanceof Collection) { Collection tags = (Collection) newmap.get("tags"); HashSet data = new HashSet(tags); newmap.put("tags", data); } try { BeanUtils.populate(nodeEntry, newmap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (null == nodeEntry.getNodename()) { throw new IllegalArgumentException("Required property 'nodename' was not specified"); } if (null == nodeEntry.getHostname()) { throw new IllegalArgumentException("Required property 'hostname' was not specified"); } if (null == nodeEntry.getAttributes()) { nodeEntry.setAttributes(new HashMap<String, String>()); } //populate attributes with any keys outside of nodeprops for (final Map.Entry<String, Object> entry : newmap.entrySet()) { if (!ResourceXMLConstants.allPropSet.contains(entry.getKey())) { nodeEntry.setAttribute(entry.getKey(), (String) entry.getValue()); } } return nodeEntry; }
public static NodeEntryImpl createFromMap(final Map<String, Object> map) throws IllegalArgumentException { final NodeEntryImpl nodeEntry = new NodeEntryImpl(); final HashMap<String, Object> newmap = new HashMap<String, Object>(map); for (final String excludeProp : excludeProps) { newmap.remove(excludeProp); } if (null != newmap.get("tags") && newmap.get("tags") instanceof String) { String tags = (String) newmap.get("tags"); String[] data; if ("".equals(tags.trim())) { data = new String[0]; } else { data = tags.split(", *"); } HashSet set = new HashSet(Arrays.asList(data)); newmap.put("tags", set); } else if (null != newmap.get("tags") && newmap.get("tags") instanceof Collection) { Collection tags = (Collection) newmap.get("tags"); HashSet data = new HashSet(); for (final Object tag : tags) { data.add(tag.toString()); } newmap.put("tags", data); }else if (null != newmap.get("tags")) { Object o = newmap.get("tags"); newmap.put("tags", new HashSet(Arrays.asList(o.toString()))); } try { BeanUtils.populate(nodeEntry, newmap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (null == nodeEntry.getNodename()) { throw new IllegalArgumentException("Required property 'nodename' was not specified"); } if (null == nodeEntry.getHostname()) { throw new IllegalArgumentException("Required property 'hostname' was not specified"); } if (null == nodeEntry.getAttributes()) { nodeEntry.setAttributes(new HashMap<String, String>()); } //populate attributes with any keys outside of nodeprops for (final Map.Entry<String, Object> entry : newmap.entrySet()) { if (!ResourceXMLConstants.allPropSet.contains(entry.getKey())) { nodeEntry.setAttribute(entry.getKey(), (String) entry.getValue()); } } return nodeEntry; }
diff --git a/src/me/confuserr/banmanager/Listeners/AsyncChat.java b/src/me/confuserr/banmanager/Listeners/AsyncChat.java index 7677834..61df3e5 100644 --- a/src/me/confuserr/banmanager/Listeners/AsyncChat.java +++ b/src/me/confuserr/banmanager/Listeners/AsyncChat.java @@ -1,48 +1,48 @@ package me.confuserr.banmanager.Listeners; import me.confuserr.banmanager.BanManager; import me.confuserr.banmanager.Util; import me.confuserr.banmanager.data.MuteData; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; public class AsyncChat implements Listener { private BanManager plugin; public AsyncChat(BanManager instance) { plugin = instance; } @EventHandler public void onPlayerChat(final AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String playerName = player.getName(); - if(plugin.getPlayerMutes().get(playerName) != null) { + if(plugin.getPlayerMute(playerName) != null) { - MuteData muteData = plugin.getPlayerMutes().get(playerName); + MuteData muteData = plugin.getPlayerMute(playerName); long expires = muteData.getExpires() * 1000; String expiresFormat = Util.formatDateDiff(expires); if(muteData.getExpires() != 0) { if(System.currentTimeMillis() < expires) { event.setCancelled(true); String mutedMessage = plugin.getMessage("tempMuted").replace("[expires]", expiresFormat).replace("[reason]", muteData.getReason()).replace("[by]", muteData.getBy()); player.sendMessage(mutedMessage); } else { // Removes them from the database and the HashMap player.sendMessage("Unmuted!"); plugin.removePlayerMute(playerName, plugin.getMessage("consoleName"), true); } } else { event.setCancelled(true); String mutedMessage = plugin.getMessage("muted").replace("[reason]", muteData.getReason()).replace("[by]", muteData.getBy()); player.sendMessage(mutedMessage); } } } }
false
true
public void onPlayerChat(final AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String playerName = player.getName(); if(plugin.getPlayerMutes().get(playerName) != null) { MuteData muteData = plugin.getPlayerMutes().get(playerName); long expires = muteData.getExpires() * 1000; String expiresFormat = Util.formatDateDiff(expires); if(muteData.getExpires() != 0) { if(System.currentTimeMillis() < expires) { event.setCancelled(true); String mutedMessage = plugin.getMessage("tempMuted").replace("[expires]", expiresFormat).replace("[reason]", muteData.getReason()).replace("[by]", muteData.getBy()); player.sendMessage(mutedMessage); } else { // Removes them from the database and the HashMap player.sendMessage("Unmuted!"); plugin.removePlayerMute(playerName, plugin.getMessage("consoleName"), true); } } else { event.setCancelled(true); String mutedMessage = plugin.getMessage("muted").replace("[reason]", muteData.getReason()).replace("[by]", muteData.getBy()); player.sendMessage(mutedMessage); } } }
public void onPlayerChat(final AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String playerName = player.getName(); if(plugin.getPlayerMute(playerName) != null) { MuteData muteData = plugin.getPlayerMute(playerName); long expires = muteData.getExpires() * 1000; String expiresFormat = Util.formatDateDiff(expires); if(muteData.getExpires() != 0) { if(System.currentTimeMillis() < expires) { event.setCancelled(true); String mutedMessage = plugin.getMessage("tempMuted").replace("[expires]", expiresFormat).replace("[reason]", muteData.getReason()).replace("[by]", muteData.getBy()); player.sendMessage(mutedMessage); } else { // Removes them from the database and the HashMap player.sendMessage("Unmuted!"); plugin.removePlayerMute(playerName, plugin.getMessage("consoleName"), true); } } else { event.setCancelled(true); String mutedMessage = plugin.getMessage("muted").replace("[reason]", muteData.getReason()).replace("[by]", muteData.getBy()); player.sendMessage(mutedMessage); } } }
diff --git a/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java b/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java index 6921c60..6181c1c 100644 --- a/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java +++ b/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java @@ -1,786 +1,787 @@ package org.darkstorm.darkbot.minecraftbot.ai; import java.util.*; import org.darkstorm.darkbot.minecraftbot.MinecraftBot; import org.darkstorm.darkbot.minecraftbot.events.*; import org.darkstorm.darkbot.minecraftbot.events.EventListener; import org.darkstorm.darkbot.minecraftbot.events.world.BlockChangeEvent; import org.darkstorm.darkbot.minecraftbot.protocol.ConnectionHandler; import org.darkstorm.darkbot.minecraftbot.protocol.bidirectional.*; import org.darkstorm.darkbot.minecraftbot.protocol.bidirectional.Packet18Animation.Animation; import org.darkstorm.darkbot.minecraftbot.protocol.writeable.*; import org.darkstorm.darkbot.minecraftbot.world.World; import org.darkstorm.darkbot.minecraftbot.world.block.*; import org.darkstorm.darkbot.minecraftbot.world.entity.*; import org.darkstorm.darkbot.minecraftbot.world.item.*; public class FarmingTask implements Task, EventListener { public enum StorageAction { STORE, SELL } private static final boolean[] UNPLACEABLE = new boolean[256]; private static final int[] HOES; private static final int[] FARMED_ITEMS; static { UNPLACEABLE[0] = true; UNPLACEABLE[8] = true; UNPLACEABLE[9] = true; UNPLACEABLE[10] = true; UNPLACEABLE[11] = true; UNPLACEABLE[26] = true; UNPLACEABLE[31] = true; UNPLACEABLE[51] = true; UNPLACEABLE[54] = true; UNPLACEABLE[61] = true; UNPLACEABLE[62] = true; UNPLACEABLE[64] = true; UNPLACEABLE[69] = true; UNPLACEABLE[71] = true; UNPLACEABLE[77] = true; UNPLACEABLE[78] = true; UNPLACEABLE[96] = true; UNPLACEABLE[107] = true; HOES = new int[] { 290, 291, 292, 293, 294 }; FARMED_ITEMS = new int[] { 372, 295, 296, 338, 361, 362, 86, 360 }; } private final MinecraftBot bot; private boolean running = false; private BlockLocation currentlyBreaking; private int ticksSinceBreak, ticksWait, itemCheckWait; private BlockLocation currentChest; private List<BlockLocation> fullChests = new ArrayList<BlockLocation>(); private BlockArea region; private StorageAction storageAction = StorageAction.STORE; private boolean selling; public FarmingTask(final MinecraftBot bot) { this.bot = bot; bot.getEventManager().registerListener(this); } @Override public synchronized boolean isPreconditionMet() { return running; } @Override public synchronized boolean start(String... options) { if(options.length > 0) { BlockLocation endpoint1 = new BlockLocation(Integer.parseInt(options[0]), Integer.parseInt(options[1]), Integer.parseInt(options[2])); BlockLocation endpoint2 = new BlockLocation(Integer.parseInt(options[3]), Integer.parseInt(options[4]), Integer.parseInt(options[5])); region = new BlockArea(endpoint1, endpoint2); } else region = null; running = true; return true; } @Override public synchronized void stop() { running = false; } @Override public synchronized void run() { if(currentlyBreaking != null) { ticksSinceBreak++; if(ticksSinceBreak > 200) currentlyBreaking = null; return; } ticksSinceBreak = 0; TaskManager taskManager = bot.getTaskManager(); EatTask eatTask = taskManager.getTaskFor(EatTask.class); if(eatTask.isActive()) return; if(ticksWait > 0) { ticksWait--; return; } MainPlayerEntity player = bot.getPlayer(); World world = bot.getWorld(); if(player == null || world == null) return; BlockLocation ourLocation = new BlockLocation(player.getLocation()); PlayerInventory inventory = player.getInventory(); boolean store = !inventory.contains(0); if(!store && storageAction.equals(StorageAction.SELL) && selling) for(int id : FARMED_ITEMS) if(inventory.getCount(id) >= 64) store = true; if(store) { System.out.println("Inventory is full!!!"); if(storageAction.equals(StorageAction.STORE)) { if(player.getWindow() instanceof ChestInventory) { System.out.println("Chest is open!!!"); ChestInventory chest = (ChestInventory) player.getWindow(); int freeSpace = -1; for(int i = 0; i < chest.getSize(); i++) if(chest.getItemAt(i) == null) freeSpace = i; if(freeSpace == -1) { if(currentChest != null) { fullChests.add(currentChest); placeBlockAt(currentChest.offset(0, 1, 0)); currentChest = null; } chest.close(); System.out.println("Closed chest, no spaces!!!"); ticksWait = 16; return; } for(int i = 0; i < 36; i++) { ItemStack item = chest.getItemAt(chest.getSize() + i); if(item == null) continue; boolean found = false; for(int id : FARMED_ITEMS) if(id == item.getId()) found = true; if(!found) continue; chest.selectItemAt(chest.getSize() + i); int index = -1; for(int j = 0; j < chest.getSize(); j++) { if(chest.getItemAt(j) == null) { index = j; break; } } if(index == -1) continue; chest.selectItemAt(index); } freeSpace = -1; for(int i = 0; i < chest.getSize(); i++) if(chest.getItemAt(i) == null) freeSpace = i; if(freeSpace == -1 && currentChest != null) { fullChests.add(currentChest); placeBlockAt(currentChest.offset(0, 1, 0)); currentChest = null; } chest.close(); currentChest = null; System.out.println("Closed chest!!!"); ticksWait = 16; return; } else { BlockLocation[] chests = getBlocks(54, 32); chestLoop: for(BlockLocation chest : chests) { if(!fullChests.contains(chest) && !isChestCovered(chest)) { BlockLocation[] surrounding = new BlockLocation[] { chest.offset(0, 1, 0), chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; int face = 0; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid())) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; if(walk.getY() > chest.getY()) face = 1; else if(walk.getX() > chest.getX()) face = 5; else if(walk.getX() < chest.getX()) face = 4; else if(walk.getZ() > chest.getZ()) face = 3; else if(walk.getZ() < chest.getZ()) face = 2; else face = 0; } } if(closestWalk == null) continue chestLoop; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) continue chestLoop; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } if(!ourLocation.equals(closestWalk)) { System.out.println("Walking to chest!!!"); bot.setActivity(new WalkActivity(bot, closestWalk)); return; } System.out.println("Opening chest!!!"); placeAt(originalWalk, face); currentChest = chest; ticksWait = 80; return; } } } } else if(storageAction.equals(StorageAction.SELL)) { if(region != null ? region.contains(ourLocation) : getClosestFarmable(32) != null) { bot.say("/spawn"); ticksWait = 200; return; } selling = true; BlockLocation[] signs = getBlocks(68, 32); signLoop: for(BlockLocation sign : signs) { TileEntity tile = world.getTileEntityAt(sign); if(tile == null || !(tile instanceof SignTileEntity)) continue; SignTileEntity signTile = (SignTileEntity) tile; String[] text = signTile.getText(); boolean found = false; if(text[0].contains("[Sell]")) for(int id : FARMED_ITEMS) if(text[2].equals(Integer.toString(id)) && inventory.getCount(id) >= 64) found = true; if(!found) continue; if(player.getDistanceTo(sign) > 3) { BlockLocation closestWalk = sign; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) continue signLoop; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } player.walkTo(closestWalk); System.out.println("Walking to sign @ " + sign); return; } BlockLocation[] surrounding = new BlockLocation[] { sign.offset(0, 1, 0), sign.offset(-1, 0, 0), sign.offset(1, 0, 0), sign.offset(0, 0, -1), sign.offset(0, 0, 1), sign.offset(0, -1, 0) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; int face = 0; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid())) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; if(walk.getY() > sign.getY()) face = 1; else if(walk.getX() > sign.getX()) face = 5; else if(walk.getX() < sign.getX()) face = 4; else if(walk.getZ() > sign.getZ()) face = 3; else if(walk.getZ() < sign.getZ()) face = 2; else face = 0; } } if(closestWalk == null) continue; placeOn(sign, face); ticksWait = 4; return; } return; } } + selling = false; BlockLocation closest = getClosestFarmable(32); if(region != null ? !region.contains(ourLocation) : closest == null) { bot.say("/home"); ticksWait = 200; return; } if(closest == null) { if(itemCheckWait > 0) { itemCheckWait--; return; } if(!inventory.contains(0)) { itemCheckWait = 10; return; } ItemEntity item = getClosestGroundItem(FARMED_ITEMS); if(item != null) { System.out.println("Item: " + item.getItem() + " Location: " + item.getLocation()); bot.setActivity(new WalkActivity(bot, new BlockLocation(item.getLocation()))); } else itemCheckWait = 10; return; } itemCheckWait = 0; System.out.println("Farming at " + closest + "!"); int id = world.getBlockIdAt(closest); if(id == 115 || id == 59 || id == 83 || id == 86 || id == 103) { System.out.println("Target: " + id + "-" + world.getBlockMetadataAt(closest)); BlockLocation walkTo = closest; if(id == 83) walkTo = closest.offset(0, -1, 0); else if(id == 86 || id == 103) { BlockLocation[] surrounding = new BlockLocation[] { closest.offset(0, 1, 0), closest.offset(-1, 0, 0), closest.offset(1, 0, 0), closest.offset(0, 0, -1), closest.offset(0, 0, 1) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid()) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; } } if(closestWalk == null) return; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) return; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } walkTo = closestWalk; } if(!ourLocation.equals(walkTo)) { bot.setActivity(new WalkActivity(bot, walkTo)); return; } breakBlock(closest); } else if(id == 88 || id == 60 || id == 3 || id == 104 || id == 105) { if(id == 104 || id == 105) { BlockLocation[] locations = new BlockLocation[] { closest.offset(-1, -1, 0), closest.offset(1, -1, 0), closest.offset(0, -1, -1), closest.offset(0, -1, -1) }; for(BlockLocation dirtLocation : locations) if(world.getBlockIdAt(dirtLocation) == 3) closest = dirtLocation; } int[] tools; if(id == 88) tools = new int[] { 372 }; else if(id == 60) tools = new int[] { 295 }; else if(((id == 3 && inventory.contains(295)) || id == 104 || id == 105) && inventory.contains(HOES)) tools = HOES; // else if(inventory.contains(338) && (id == 3 || id == 12)) // tools = new int[] { 338 }; else return; if(!switchTo(tools)) return; BlockLocation offset = closest.offset(0, 1, 0); if(!ourLocation.equals(offset)) { bot.setActivity(new WalkActivity(bot, offset)); return; } placeAt(offset); ticksWait = 5; } } private ItemEntity getClosestGroundItem(int... ids) { MainPlayerEntity player = bot.getPlayer(); World world = bot.getWorld(); if(player == null || world == null) return null; Entity[] entities = world.getEntities(); ItemEntity closest = null; int closestDistance = Integer.MAX_VALUE; for(Entity entity : entities) { if(entity instanceof ItemEntity) { ItemEntity item = (ItemEntity) entity; if(item.getItem() == null) continue; int itemId = item.getItem().getId(); for(int id : ids) { if(itemId == id) { int distance = player.getDistanceToSquared(item); if(distance < closestDistance) { int blockId = world.getBlockIdAt(new BlockLocation(item.getLocation())); if(!BlockType.getById(blockId).isSolid()) { closest = item; closestDistance = distance; } } } } } } return closest; } private boolean isChestCovered(BlockLocation chest) { if(checkChest(chest)) return true; BlockLocation[] surrounding = new BlockLocation[] { chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) }; for(BlockLocation otherChest : surrounding) if(bot.getWorld().getBlockIdAt(otherChest) == 54 && checkChest(otherChest)) return true; return false; } private boolean checkChest(BlockLocation chest) { int idAbove = bot.getWorld().getBlockIdAt(chest.offset(0, 1, 0)); if(!BlockType.getById(idAbove).isSolid()) return false; BlockType[] noncovers = new BlockType[] { BlockType.CHEST, BlockType.ENDER_CHEST, BlockType.STEP, BlockType.BED_BLOCK, BlockType.ANVIL, BlockType.BREWING_STAND, BlockType.WOOD_STEP, BlockType.WOOD_STAIRS, BlockType.BRICK_STAIRS, BlockType.COBBLESTONE_STAIRS, BlockType.NETHER_BRICK_STAIRS, BlockType.SANDSTONE_STAIRS, BlockType.SMOOTH_STAIRS }; for(BlockType type : noncovers) if(idAbove == type.getId()) return false; return true; } @Override public synchronized boolean isActive() { return running; } @EventHandler public synchronized void onBlockChange(BlockChangeEvent event) { BlockLocation location = event.getLocation(); Block newBlock = event.getNewBlock(); if((event.getOldBlock() == null && newBlock == null) || (event.getOldBlock() != null && newBlock != null && event.getOldBlock().getId() == newBlock.getId())) return; if(newBlock == null || newBlock.getId() == 0) { if(currentlyBreaking != null && currentlyBreaking.equals(location)) { currentlyBreaking = null; } } } private BlockLocation getClosestFarmable(int radius) { MainPlayerEntity player = bot.getPlayer(); World world = bot.getWorld(); if(player == null || world == null) return null; PlayerInventory inventory = player.getInventory(); boolean hasNetherwarts = inventory.contains(372), hasSeeds = inventory.contains(295), hasHoe = inventory.contains(HOES); // boolean hasReeds = inventory.contains(338); BlockLocation ourLocation = new BlockLocation(player.getLocation()); List<BlockLocation> closest = new ArrayList<>(); int closestDistance = Integer.MAX_VALUE, actualFarmType = 0; for(int x = region != null ? region.getX() - ourLocation.getX() : -radius; x < (region != null ? region.getX() + region.getWidth() - ourLocation.getX() : radius); x++) { for(int y = region != null ? region.getY() - ourLocation.getY() : -radius / 2; y < (region != null ? region.getY() + region.getHeight() - ourLocation.getY() : radius / 2); y++) { for(int z = region != null ? region.getZ() - ourLocation.getZ() : -radius; z < (region != null ? region.getZ() + region.getLength() - ourLocation.getZ() : radius); z++) { BlockLocation location = new BlockLocation(ourLocation.getX() + x, ourLocation.getY() + y, ourLocation.getZ() + z); int distance = ourLocation.getDistanceToSquared(location); if(distance <= closestDistance) { // System.out.println("[" + x + "," + y + "," + z + "] " // + distance + " -> " + closestDistance); int id = world.getBlockIdAt(location); int idAbove = world.getBlockIdAt(location.offset(0, 1, 0)); int idBelow = world.getBlockIdAt(location.offset(0, -1, 0)); int metadata = world.getBlockMetadataAt(location); boolean pumpkinWatermelonDirt = false; boolean plantSeeds = true; int farmType = actualFarmType; if(farmType <= 3 && (id == 104 || id == 105) && hasHoe) { BlockLocation[] locations = new BlockLocation[] { location.offset(-1, -1, 0), location.offset(1, -1, 0), location.offset(0, -1, -1), location.offset(0, -1, 1) }; for(BlockLocation dirtLocation : locations) if(world.getBlockIdAt(dirtLocation) == 3 && world.getBlockIdAt(dirtLocation.offset(0, 1, 0)) == 0) pumpkinWatermelonDirt = true; } if(farmType <= 1 && (id == 3 && idAbove == 0 && hasHoe && hasSeeds)) { BlockLocation[] locations = new BlockLocation[] { location.offset(-1, 0, 0), location.offset(1, 0, 0), location.offset(0, 0, -1), location.offset(0, 0, 1) }; for(BlockLocation adjacent : locations) { int adjacentId = world.getBlockIdAt(adjacent); if(adjacentId == 104 || adjacentId == 105) plantSeeds = false; } } if(farmType <= 3 && (pumpkinWatermelonDirt || id == 103 || id == 86 || (id == 115 && metadata > 2) || (id == 59 && metadata > 6) || (id == 83 && idBelow == 83 && idAbove == 83))) { farmType = 3; } else if(farmType <= 2 && ((id == 88 && idAbove == 0 && hasNetherwarts) || (id == 60 && idAbove == 0 && hasSeeds))) farmType = 2; // else if(farmType < 2 // && ((id == 3 || id == 12) && idAbove == 0 && // hasReeds)) // farmType = 2; else if(farmType <= 1 && (id == 3 && idAbove == 0 && hasHoe && hasSeeds && plantSeeds)) farmType = 1; else continue; if(distance == closestDistance) { if(farmType != actualFarmType) continue; } else closest.clear(); closest.add(location); actualFarmType = farmType; closestDistance = distance; } } } } BlockLocation closestLocation = null; if(closest.size() > 0) closestLocation = closest.get((int) (Math.random() * closest.size())); return closestLocation; } @SuppressWarnings("unused") private BlockLocation getClosestBlock(int id, int radius) { MainPlayerEntity player = bot.getPlayer(); if(player == null) return null; BlockLocation ourLocation = new BlockLocation((int) (Math.round(player.getX() - 0.5)), (int) player.getY(), (int) (Math.round(player.getZ() - 0.5))); BlockLocation closest = null; int closestDistance = Integer.MAX_VALUE; for(BlockLocation location : getBlocks(id, radius)) { int distance = ourLocation.getDistanceToSquared(location); if(distance < closestDistance) { closest = location; closestDistance = distance; } } return closest; } private BlockLocation[] getBlocks(int id, int radius) { MainPlayerEntity player = bot.getPlayer(); World world = bot.getWorld(); if(player == null || world == null) return new BlockLocation[0]; BlockLocation ourLocation = new BlockLocation(player.getLocation()); BlockArea region = this.region; if(region != null && !region.contains(ourLocation)) region = null; List<BlockLocation> blocks = new ArrayList<BlockLocation>(); for(int x = region != null ? region.getX() - ourLocation.getX() : -radius; x < (region != null ? region.getX() + region.getWidth() - ourLocation.getX() : radius); x++) { for(int y = region != null ? region.getY() - ourLocation.getY() : -radius / 2; y < (region != null ? region.getY() + region.getHeight() - ourLocation.getY() : radius / 2); y++) { for(int z = region != null ? region.getZ() - ourLocation.getZ() : -radius; z < (region != null ? region.getZ() + region.getLength() - ourLocation.getZ() : radius); z++) { BlockLocation location = new BlockLocation(ourLocation.getX() + x, ourLocation.getY() + y, ourLocation.getZ() + z); if(world.getBlockIdAt(location) == id) blocks.add(location); } } } return blocks.toArray(new BlockLocation[blocks.size()]); } private boolean switchTo(int... toolIds) { MainPlayerEntity player = bot.getPlayer(); if(player == null) return false; PlayerInventory inventory = player.getInventory(); int slot = -1; label: for(int i = 0; i < 36; i++) { ItemStack item = inventory.getItemAt(i); if(item == null) continue; int id = item.getId(); for(int toolId : toolIds) { if(id == toolId) { slot = i; break label; } } } if(slot == -1) return false; if(inventory.getCurrentHeldSlot() != slot) { if(slot > 8) { int hotbarSpace = 9; for(int hotbarIndex = 0; hotbarIndex < 9; hotbarIndex++) { if(inventory.getItemAt(hotbarIndex) == null) { hotbarSpace = hotbarIndex; break; } else if(hotbarIndex < hotbarSpace) hotbarSpace = hotbarIndex; } if(hotbarSpace == 9) return false; inventory.selectItemAt(slot); inventory.selectItemAt(hotbarSpace); if(inventory.getSelectedItem() != null) inventory.selectItemAt(slot); inventory.close(); slot = hotbarSpace; } inventory.setCurrentHeldSlot(slot); } return true; } private void breakBlock(BlockLocation location) { int x = location.getX(), y = location.getY(), z = location.getZ(); MainPlayerEntity player = bot.getPlayer(); if(player == null) return; player.face(x, y, z); ConnectionHandler connectionHandler = bot.getConnectionHandler(); connectionHandler.sendPacket(new Packet12PlayerLook((float) player.getYaw(), (float) player.getPitch(), true)); connectionHandler.sendPacket(new Packet18Animation(player.getId(), Animation.SWING_ARM)); connectionHandler.sendPacket(new Packet14BlockDig(0, x, y, z, 0)); connectionHandler.sendPacket(new Packet14BlockDig(2, x, y, z, 0)); currentlyBreaking = location; } private boolean placeBlockAt(BlockLocation location) { MainPlayerEntity player = bot.getPlayer(); if(player == null) return false; PlayerInventory inventory = player.getInventory(); int slot = -1; for(int i = 0; i < 36; i++) { ItemStack item = inventory.getItemAt(i); if(item == null) continue; int id = item.getId(); if(id == 1 || id == 3 || id == 4) { slot = i; break; } } if(slot == -1) return false; if(!player.switchHeldItems(slot)) return false; if(player.placeBlock(location)) return true; return false; } private void placeAt(BlockLocation location) { placeAt(location, getPlacementBlockFaceAt(location)); } private void placeAt(BlockLocation location, int face) { MainPlayerEntity player = bot.getPlayer(); if(player == null) return; PlayerInventory inventory = player.getInventory(); int originalX = location.getX(), originalY = location.getY(), originalZ = location.getZ(); location = getOffsetBlock(location, face); if(location == null) return; int x = location.getX(), y = location.getY(), z = location.getZ(); player.face(x + ((originalX - x) / 2.0D) + 0.5, y + ((originalY - y) / 2.0D), z + ((originalZ - z) / 2.0D) + 0.5); ConnectionHandler connectionHandler = bot.getConnectionHandler(); connectionHandler.sendPacket(new Packet12PlayerLook((float) player.getYaw(), (float) player.getPitch(), true)); connectionHandler.sendPacket(new Packet18Animation(player.getId(), Animation.SWING_ARM)); Packet15Place placePacket = new Packet15Place(); placePacket.xPosition = x; placePacket.yPosition = y; placePacket.zPosition = z; placePacket.direction = face; placePacket.itemStack = inventory.getCurrentHeldItem(); connectionHandler.sendPacket(placePacket); ticksWait = 4; } private void placeOn(BlockLocation location, int face) { MainPlayerEntity player = bot.getPlayer(); if(player == null) return; PlayerInventory inventory = player.getInventory(); int x = location.getX(), y = location.getY(), z = location.getZ(); location = getOffsetBlock(location, face); if(location == null) return; int originalX = location.getX(), originalY = location.getY(), originalZ = location.getZ(); player.face(x + ((originalX - x) / 2.0D) + 0.5, y + ((originalY - y) / 2.0D), z + ((originalZ - z) / 2.0D) + 0.5); ConnectionHandler connectionHandler = bot.getConnectionHandler(); connectionHandler.sendPacket(new Packet12PlayerLook((float) player.getYaw(), (float) player.getPitch(), true)); connectionHandler.sendPacket(new Packet18Animation(player.getId(), Animation.SWING_ARM)); Packet15Place placePacket = new Packet15Place(); placePacket.xPosition = x; placePacket.yPosition = y; placePacket.zPosition = z; placePacket.direction = face; placePacket.itemStack = inventory.getCurrentHeldItem(); connectionHandler.sendPacket(placePacket); ticksWait = 4; } private int getPlacementBlockFaceAt(BlockLocation location) { int x = location.getX(), y = location.getY(), z = location.getZ(); World world = bot.getWorld(); if(!UNPLACEABLE[world.getBlockIdAt(x, y - 1, z)]) { return 1; } else if(!UNPLACEABLE[world.getBlockIdAt(x, y + 1, z)]) { return 0; } else if(!UNPLACEABLE[world.getBlockIdAt(x + 1, y, z)]) { return 4; } else if(!UNPLACEABLE[world.getBlockIdAt(x, y, z - 1)]) { return 3; } else if(!UNPLACEABLE[world.getBlockIdAt(x, y, z + 1)]) { return 2; } else if(!UNPLACEABLE[world.getBlockIdAt(x - 1, y, z)]) { return 5; } else return -1; } private BlockLocation getOffsetBlock(BlockLocation location, int face) { int x = location.getX(), y = location.getY(), z = location.getZ(); switch(face) { case 0: y++; break; case 1: y--; break; case 2: z++; break; case 3: z--; break; case 4: x++; break; case 5: x--; break; default: return null; } return new BlockLocation(x, y, z); } public StorageAction getStorageAction() { return storageAction; } public void setStorageAction(StorageAction storageAction) { this.storageAction = storageAction; } @Override public TaskPriority getPriority() { return TaskPriority.NORMAL; } @Override public boolean isExclusive() { return false; } @Override public boolean ignoresExclusive() { return false; } @Override public String getName() { return "Farm"; } @Override public String getOptionDescription() { return "[<x1> <y1> <z1> <x2> <y2> <z2>]"; } }
true
true
public synchronized void run() { if(currentlyBreaking != null) { ticksSinceBreak++; if(ticksSinceBreak > 200) currentlyBreaking = null; return; } ticksSinceBreak = 0; TaskManager taskManager = bot.getTaskManager(); EatTask eatTask = taskManager.getTaskFor(EatTask.class); if(eatTask.isActive()) return; if(ticksWait > 0) { ticksWait--; return; } MainPlayerEntity player = bot.getPlayer(); World world = bot.getWorld(); if(player == null || world == null) return; BlockLocation ourLocation = new BlockLocation(player.getLocation()); PlayerInventory inventory = player.getInventory(); boolean store = !inventory.contains(0); if(!store && storageAction.equals(StorageAction.SELL) && selling) for(int id : FARMED_ITEMS) if(inventory.getCount(id) >= 64) store = true; if(store) { System.out.println("Inventory is full!!!"); if(storageAction.equals(StorageAction.STORE)) { if(player.getWindow() instanceof ChestInventory) { System.out.println("Chest is open!!!"); ChestInventory chest = (ChestInventory) player.getWindow(); int freeSpace = -1; for(int i = 0; i < chest.getSize(); i++) if(chest.getItemAt(i) == null) freeSpace = i; if(freeSpace == -1) { if(currentChest != null) { fullChests.add(currentChest); placeBlockAt(currentChest.offset(0, 1, 0)); currentChest = null; } chest.close(); System.out.println("Closed chest, no spaces!!!"); ticksWait = 16; return; } for(int i = 0; i < 36; i++) { ItemStack item = chest.getItemAt(chest.getSize() + i); if(item == null) continue; boolean found = false; for(int id : FARMED_ITEMS) if(id == item.getId()) found = true; if(!found) continue; chest.selectItemAt(chest.getSize() + i); int index = -1; for(int j = 0; j < chest.getSize(); j++) { if(chest.getItemAt(j) == null) { index = j; break; } } if(index == -1) continue; chest.selectItemAt(index); } freeSpace = -1; for(int i = 0; i < chest.getSize(); i++) if(chest.getItemAt(i) == null) freeSpace = i; if(freeSpace == -1 && currentChest != null) { fullChests.add(currentChest); placeBlockAt(currentChest.offset(0, 1, 0)); currentChest = null; } chest.close(); currentChest = null; System.out.println("Closed chest!!!"); ticksWait = 16; return; } else { BlockLocation[] chests = getBlocks(54, 32); chestLoop: for(BlockLocation chest : chests) { if(!fullChests.contains(chest) && !isChestCovered(chest)) { BlockLocation[] surrounding = new BlockLocation[] { chest.offset(0, 1, 0), chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; int face = 0; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid())) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; if(walk.getY() > chest.getY()) face = 1; else if(walk.getX() > chest.getX()) face = 5; else if(walk.getX() < chest.getX()) face = 4; else if(walk.getZ() > chest.getZ()) face = 3; else if(walk.getZ() < chest.getZ()) face = 2; else face = 0; } } if(closestWalk == null) continue chestLoop; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) continue chestLoop; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } if(!ourLocation.equals(closestWalk)) { System.out.println("Walking to chest!!!"); bot.setActivity(new WalkActivity(bot, closestWalk)); return; } System.out.println("Opening chest!!!"); placeAt(originalWalk, face); currentChest = chest; ticksWait = 80; return; } } } } else if(storageAction.equals(StorageAction.SELL)) { if(region != null ? region.contains(ourLocation) : getClosestFarmable(32) != null) { bot.say("/spawn"); ticksWait = 200; return; } selling = true; BlockLocation[] signs = getBlocks(68, 32); signLoop: for(BlockLocation sign : signs) { TileEntity tile = world.getTileEntityAt(sign); if(tile == null || !(tile instanceof SignTileEntity)) continue; SignTileEntity signTile = (SignTileEntity) tile; String[] text = signTile.getText(); boolean found = false; if(text[0].contains("[Sell]")) for(int id : FARMED_ITEMS) if(text[2].equals(Integer.toString(id)) && inventory.getCount(id) >= 64) found = true; if(!found) continue; if(player.getDistanceTo(sign) > 3) { BlockLocation closestWalk = sign; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) continue signLoop; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } player.walkTo(closestWalk); System.out.println("Walking to sign @ " + sign); return; } BlockLocation[] surrounding = new BlockLocation[] { sign.offset(0, 1, 0), sign.offset(-1, 0, 0), sign.offset(1, 0, 0), sign.offset(0, 0, -1), sign.offset(0, 0, 1), sign.offset(0, -1, 0) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; int face = 0; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid())) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; if(walk.getY() > sign.getY()) face = 1; else if(walk.getX() > sign.getX()) face = 5; else if(walk.getX() < sign.getX()) face = 4; else if(walk.getZ() > sign.getZ()) face = 3; else if(walk.getZ() < sign.getZ()) face = 2; else face = 0; } } if(closestWalk == null) continue; placeOn(sign, face); ticksWait = 4; return; } return; } } BlockLocation closest = getClosestFarmable(32); if(region != null ? !region.contains(ourLocation) : closest == null) { bot.say("/home"); ticksWait = 200; return; } if(closest == null) { if(itemCheckWait > 0) { itemCheckWait--; return; } if(!inventory.contains(0)) { itemCheckWait = 10; return; } ItemEntity item = getClosestGroundItem(FARMED_ITEMS); if(item != null) { System.out.println("Item: " + item.getItem() + " Location: " + item.getLocation()); bot.setActivity(new WalkActivity(bot, new BlockLocation(item.getLocation()))); } else itemCheckWait = 10; return; } itemCheckWait = 0; System.out.println("Farming at " + closest + "!"); int id = world.getBlockIdAt(closest); if(id == 115 || id == 59 || id == 83 || id == 86 || id == 103) { System.out.println("Target: " + id + "-" + world.getBlockMetadataAt(closest)); BlockLocation walkTo = closest; if(id == 83) walkTo = closest.offset(0, -1, 0); else if(id == 86 || id == 103) { BlockLocation[] surrounding = new BlockLocation[] { closest.offset(0, 1, 0), closest.offset(-1, 0, 0), closest.offset(1, 0, 0), closest.offset(0, 0, -1), closest.offset(0, 0, 1) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid()) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; } } if(closestWalk == null) return; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) return; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } walkTo = closestWalk; } if(!ourLocation.equals(walkTo)) { bot.setActivity(new WalkActivity(bot, walkTo)); return; } breakBlock(closest); } else if(id == 88 || id == 60 || id == 3 || id == 104 || id == 105) { if(id == 104 || id == 105) { BlockLocation[] locations = new BlockLocation[] { closest.offset(-1, -1, 0), closest.offset(1, -1, 0), closest.offset(0, -1, -1), closest.offset(0, -1, -1) }; for(BlockLocation dirtLocation : locations) if(world.getBlockIdAt(dirtLocation) == 3) closest = dirtLocation; } int[] tools; if(id == 88) tools = new int[] { 372 }; else if(id == 60) tools = new int[] { 295 }; else if(((id == 3 && inventory.contains(295)) || id == 104 || id == 105) && inventory.contains(HOES)) tools = HOES; // else if(inventory.contains(338) && (id == 3 || id == 12)) // tools = new int[] { 338 }; else return; if(!switchTo(tools)) return; BlockLocation offset = closest.offset(0, 1, 0); if(!ourLocation.equals(offset)) { bot.setActivity(new WalkActivity(bot, offset)); return; } placeAt(offset); ticksWait = 5; } }
public synchronized void run() { if(currentlyBreaking != null) { ticksSinceBreak++; if(ticksSinceBreak > 200) currentlyBreaking = null; return; } ticksSinceBreak = 0; TaskManager taskManager = bot.getTaskManager(); EatTask eatTask = taskManager.getTaskFor(EatTask.class); if(eatTask.isActive()) return; if(ticksWait > 0) { ticksWait--; return; } MainPlayerEntity player = bot.getPlayer(); World world = bot.getWorld(); if(player == null || world == null) return; BlockLocation ourLocation = new BlockLocation(player.getLocation()); PlayerInventory inventory = player.getInventory(); boolean store = !inventory.contains(0); if(!store && storageAction.equals(StorageAction.SELL) && selling) for(int id : FARMED_ITEMS) if(inventory.getCount(id) >= 64) store = true; if(store) { System.out.println("Inventory is full!!!"); if(storageAction.equals(StorageAction.STORE)) { if(player.getWindow() instanceof ChestInventory) { System.out.println("Chest is open!!!"); ChestInventory chest = (ChestInventory) player.getWindow(); int freeSpace = -1; for(int i = 0; i < chest.getSize(); i++) if(chest.getItemAt(i) == null) freeSpace = i; if(freeSpace == -1) { if(currentChest != null) { fullChests.add(currentChest); placeBlockAt(currentChest.offset(0, 1, 0)); currentChest = null; } chest.close(); System.out.println("Closed chest, no spaces!!!"); ticksWait = 16; return; } for(int i = 0; i < 36; i++) { ItemStack item = chest.getItemAt(chest.getSize() + i); if(item == null) continue; boolean found = false; for(int id : FARMED_ITEMS) if(id == item.getId()) found = true; if(!found) continue; chest.selectItemAt(chest.getSize() + i); int index = -1; for(int j = 0; j < chest.getSize(); j++) { if(chest.getItemAt(j) == null) { index = j; break; } } if(index == -1) continue; chest.selectItemAt(index); } freeSpace = -1; for(int i = 0; i < chest.getSize(); i++) if(chest.getItemAt(i) == null) freeSpace = i; if(freeSpace == -1 && currentChest != null) { fullChests.add(currentChest); placeBlockAt(currentChest.offset(0, 1, 0)); currentChest = null; } chest.close(); currentChest = null; System.out.println("Closed chest!!!"); ticksWait = 16; return; } else { BlockLocation[] chests = getBlocks(54, 32); chestLoop: for(BlockLocation chest : chests) { if(!fullChests.contains(chest) && !isChestCovered(chest)) { BlockLocation[] surrounding = new BlockLocation[] { chest.offset(0, 1, 0), chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; int face = 0; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid())) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; if(walk.getY() > chest.getY()) face = 1; else if(walk.getX() > chest.getX()) face = 5; else if(walk.getX() < chest.getX()) face = 4; else if(walk.getZ() > chest.getZ()) face = 3; else if(walk.getZ() < chest.getZ()) face = 2; else face = 0; } } if(closestWalk == null) continue chestLoop; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) continue chestLoop; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } if(!ourLocation.equals(closestWalk)) { System.out.println("Walking to chest!!!"); bot.setActivity(new WalkActivity(bot, closestWalk)); return; } System.out.println("Opening chest!!!"); placeAt(originalWalk, face); currentChest = chest; ticksWait = 80; return; } } } } else if(storageAction.equals(StorageAction.SELL)) { if(region != null ? region.contains(ourLocation) : getClosestFarmable(32) != null) { bot.say("/spawn"); ticksWait = 200; return; } selling = true; BlockLocation[] signs = getBlocks(68, 32); signLoop: for(BlockLocation sign : signs) { TileEntity tile = world.getTileEntityAt(sign); if(tile == null || !(tile instanceof SignTileEntity)) continue; SignTileEntity signTile = (SignTileEntity) tile; String[] text = signTile.getText(); boolean found = false; if(text[0].contains("[Sell]")) for(int id : FARMED_ITEMS) if(text[2].equals(Integer.toString(id)) && inventory.getCount(id) >= 64) found = true; if(!found) continue; if(player.getDistanceTo(sign) > 3) { BlockLocation closestWalk = sign; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) continue signLoop; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } player.walkTo(closestWalk); System.out.println("Walking to sign @ " + sign); return; } BlockLocation[] surrounding = new BlockLocation[] { sign.offset(0, 1, 0), sign.offset(-1, 0, 0), sign.offset(1, 0, 0), sign.offset(0, 0, -1), sign.offset(0, 0, 1), sign.offset(0, -1, 0) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; int face = 0; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid())) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; if(walk.getY() > sign.getY()) face = 1; else if(walk.getX() > sign.getX()) face = 5; else if(walk.getX() < sign.getX()) face = 4; else if(walk.getZ() > sign.getZ()) face = 3; else if(walk.getZ() < sign.getZ()) face = 2; else face = 0; } } if(closestWalk == null) continue; placeOn(sign, face); ticksWait = 4; return; } return; } } selling = false; BlockLocation closest = getClosestFarmable(32); if(region != null ? !region.contains(ourLocation) : closest == null) { bot.say("/home"); ticksWait = 200; return; } if(closest == null) { if(itemCheckWait > 0) { itemCheckWait--; return; } if(!inventory.contains(0)) { itemCheckWait = 10; return; } ItemEntity item = getClosestGroundItem(FARMED_ITEMS); if(item != null) { System.out.println("Item: " + item.getItem() + " Location: " + item.getLocation()); bot.setActivity(new WalkActivity(bot, new BlockLocation(item.getLocation()))); } else itemCheckWait = 10; return; } itemCheckWait = 0; System.out.println("Farming at " + closest + "!"); int id = world.getBlockIdAt(closest); if(id == 115 || id == 59 || id == 83 || id == 86 || id == 103) { System.out.println("Target: " + id + "-" + world.getBlockMetadataAt(closest)); BlockLocation walkTo = closest; if(id == 83) walkTo = closest.offset(0, -1, 0); else if(id == 86 || id == 103) { BlockLocation[] surrounding = new BlockLocation[] { closest.offset(0, 1, 0), closest.offset(-1, 0, 0), closest.offset(1, 0, 0), closest.offset(0, 0, -1), closest.offset(0, 0, 1) }; BlockLocation closestWalk = null; int closestDistance = Integer.MAX_VALUE; for(BlockLocation walk : surrounding) { if(BlockType.getById(world.getBlockIdAt(walk)).isSolid()) continue; int distance = ourLocation.getDistanceToSquared(walk); if(distance < closestDistance) { closestWalk = walk; closestDistance = distance; } } if(closestWalk == null) return; BlockLocation originalWalk = closestWalk; BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0); while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) { closestWalk = closestWalkOffset; if(originalWalk.getY() - closestWalkOffset.getY() > 5) return; closestWalkOffset = closestWalkOffset.offset(0, -1, 0); } walkTo = closestWalk; } if(!ourLocation.equals(walkTo)) { bot.setActivity(new WalkActivity(bot, walkTo)); return; } breakBlock(closest); } else if(id == 88 || id == 60 || id == 3 || id == 104 || id == 105) { if(id == 104 || id == 105) { BlockLocation[] locations = new BlockLocation[] { closest.offset(-1, -1, 0), closest.offset(1, -1, 0), closest.offset(0, -1, -1), closest.offset(0, -1, -1) }; for(BlockLocation dirtLocation : locations) if(world.getBlockIdAt(dirtLocation) == 3) closest = dirtLocation; } int[] tools; if(id == 88) tools = new int[] { 372 }; else if(id == 60) tools = new int[] { 295 }; else if(((id == 3 && inventory.contains(295)) || id == 104 || id == 105) && inventory.contains(HOES)) tools = HOES; // else if(inventory.contains(338) && (id == 3 || id == 12)) // tools = new int[] { 338 }; else return; if(!switchTo(tools)) return; BlockLocation offset = closest.offset(0, 1, 0); if(!ourLocation.equals(offset)) { bot.setActivity(new WalkActivity(bot, offset)); return; } placeAt(offset); ticksWait = 5; } }
diff --git a/xfire-spring/src/test/org/codehaus/xfire/spring/config/XFireConfigLoaderTest.java b/xfire-spring/src/test/org/codehaus/xfire/spring/config/XFireConfigLoaderTest.java index 1014c7d7..1d4635d2 100644 --- a/xfire-spring/src/test/org/codehaus/xfire/spring/config/XFireConfigLoaderTest.java +++ b/xfire-spring/src/test/org/codehaus/xfire/spring/config/XFireConfigLoaderTest.java @@ -1,132 +1,132 @@ package org.codehaus.xfire.spring.config; import javax.servlet.ServletContext; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.codehaus.xfire.XFire; import org.codehaus.xfire.handler.Handler; import org.codehaus.xfire.service.Endpoint; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.invoker.BeanInvoker; import org.codehaus.xfire.service.invoker.Invoker; import org.codehaus.xfire.service.invoker.ObjectInvoker; import org.codehaus.xfire.spring.AbstractXFireSpringTest; import org.codehaus.xfire.spring.ServiceBean; import org.codehaus.xfire.spring.TestHandler; import org.codehaus.xfire.spring.XFireConfigLoader; import org.codehaus.xfire.test.Echo; import org.codehaus.xfire.test.EchoImpl; import org.codehaus.xfire.transport.http.SoapHttpTransport; import org.springframework.context.ApplicationContext; import org.springframework.mock.web.MockServletContext; /** * @author tomeks * */ public class XFireConfigLoaderTest extends AbstractXFireSpringTest { public void testConfigLoader() throws Exception { XFireConfigLoader configLoader = new XFireConfigLoader(); XFire xfire = configLoader.loadConfig("META-INF/xfire/sservices.xml", null); doAssertions(xfire); } public void testConfigLoaderWithFilesystem() throws Exception { XFireConfigLoader configLoader = new XFireConfigLoader(); XFire xfire = configLoader.loadConfig(getTestFile("src/test/META-INF/xfire/sservices.xml").getAbsolutePath()); doAssertions(xfire); } public void testConfigLoaderWithMultipleFiles() throws Exception { XFireConfigLoader configLoader = new XFireConfigLoader(); configLoader.setBasedir(getTestFile(".")); XFire xfire = configLoader.loadConfig("src/test/META-INF/xfire/sservices.xml, " + "org/codehaus/xfire/spring/config/OperationMetadataServices.xml"); doAssertions(xfire); } public void testConfigLoaderWithParentContext() throws Exception { ServletContext servletCtx = new MockServletContext(); ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext(new String[] {"org/codehaus/xfire/spring/xfire.xml"}); XFireConfigLoader configLoader = new XFireConfigLoader(); XFire xfire = configLoader.loadConfig("META-INF/xfire/sservices.xml", appCtx); doAssertions(xfire); } private void doAssertions(XFire xfire){ assertNotNull(xfire); assertEquals(2, xfire.getInHandlers().size()); assertTrue(xfire.getInHandlers().get(1) instanceof TestHandler); assertEquals(xfire.getOutHandlers().size(),1); assertEquals(xfire.getFaultHandlers().size(),1); Service service = xfire.getServiceRegistry().getService("testservice"); assertNotNull(service); assertEquals(4, service.getBindings().size()); assertNotNull(service.getBinding(SoapHttpTransport.SOAP11_HTTP_BINDING)); assertNotNull(service.getBinding(SoapHttpTransport.SOAP12_HTTP_BINDING)); assertEquals(1, service.getEndpoints().size()); Endpoint ep = (Endpoint) service.getEndpoints().iterator().next(); assertNotNull(ep); assertEquals("http://localhost/TestService", ep.getUrl()); - assertEquals(2, service.getInHandlers().size()); - Handler testHandler = (Handler) service.getInHandlers().get(1); + assertEquals(3, service.getInHandlers().size()); + Handler testHandler = (Handler) service.getInHandlers().get(2); assertTrue(testHandler instanceof TestHandler); assertEquals(testHandler.getAfter().size(),1); assertEquals(testHandler.getBefore().size(),2); assertEquals(service.getOutHandlers().size(),1); assertEquals("value", service.getProperty("myKey")); assertEquals("value1", service.getProperty("myKey1")); service = xfire.getServiceRegistry().getService("EchoWithJustImpl"); assertEquals(EchoImpl.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithBean"); Invoker invoker = service.getInvoker(); assertTrue(invoker instanceof BeanInvoker); assertEquals(Echo.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithBeanNoServiceClass"); invoker = service.getInvoker(); assertTrue(invoker instanceof BeanInvoker); assertEquals(EchoImpl.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithSchemas"); ServiceBean serviceBean = (ServiceBean) getBean("EchoWithServiceFactory"); assertTrue(serviceBean.getServiceFactory() instanceof CustomServiceFactory); serviceBean = (ServiceBean) getBean("EchoWithBeanServiceFactory"); assertTrue(serviceBean.getServiceFactory() instanceof CustomServiceFactory); serviceBean = (ServiceBean) getBean("EchoWithInvoker"); assertTrue(serviceBean.getInvoker() instanceof ObjectInvoker); } protected ApplicationContext createContext() { return new ClassPathXmlApplicationContext(new String[] { "org/codehaus/xfire/spring/xfire.xml", "META-INF/xfire/sservices.xml" }); } }
true
true
private void doAssertions(XFire xfire){ assertNotNull(xfire); assertEquals(2, xfire.getInHandlers().size()); assertTrue(xfire.getInHandlers().get(1) instanceof TestHandler); assertEquals(xfire.getOutHandlers().size(),1); assertEquals(xfire.getFaultHandlers().size(),1); Service service = xfire.getServiceRegistry().getService("testservice"); assertNotNull(service); assertEquals(4, service.getBindings().size()); assertNotNull(service.getBinding(SoapHttpTransport.SOAP11_HTTP_BINDING)); assertNotNull(service.getBinding(SoapHttpTransport.SOAP12_HTTP_BINDING)); assertEquals(1, service.getEndpoints().size()); Endpoint ep = (Endpoint) service.getEndpoints().iterator().next(); assertNotNull(ep); assertEquals("http://localhost/TestService", ep.getUrl()); assertEquals(2, service.getInHandlers().size()); Handler testHandler = (Handler) service.getInHandlers().get(1); assertTrue(testHandler instanceof TestHandler); assertEquals(testHandler.getAfter().size(),1); assertEquals(testHandler.getBefore().size(),2); assertEquals(service.getOutHandlers().size(),1); assertEquals("value", service.getProperty("myKey")); assertEquals("value1", service.getProperty("myKey1")); service = xfire.getServiceRegistry().getService("EchoWithJustImpl"); assertEquals(EchoImpl.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithBean"); Invoker invoker = service.getInvoker(); assertTrue(invoker instanceof BeanInvoker); assertEquals(Echo.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithBeanNoServiceClass"); invoker = service.getInvoker(); assertTrue(invoker instanceof BeanInvoker); assertEquals(EchoImpl.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithSchemas"); ServiceBean serviceBean = (ServiceBean) getBean("EchoWithServiceFactory"); assertTrue(serviceBean.getServiceFactory() instanceof CustomServiceFactory); serviceBean = (ServiceBean) getBean("EchoWithBeanServiceFactory"); assertTrue(serviceBean.getServiceFactory() instanceof CustomServiceFactory); serviceBean = (ServiceBean) getBean("EchoWithInvoker"); assertTrue(serviceBean.getInvoker() instanceof ObjectInvoker); }
private void doAssertions(XFire xfire){ assertNotNull(xfire); assertEquals(2, xfire.getInHandlers().size()); assertTrue(xfire.getInHandlers().get(1) instanceof TestHandler); assertEquals(xfire.getOutHandlers().size(),1); assertEquals(xfire.getFaultHandlers().size(),1); Service service = xfire.getServiceRegistry().getService("testservice"); assertNotNull(service); assertEquals(4, service.getBindings().size()); assertNotNull(service.getBinding(SoapHttpTransport.SOAP11_HTTP_BINDING)); assertNotNull(service.getBinding(SoapHttpTransport.SOAP12_HTTP_BINDING)); assertEquals(1, service.getEndpoints().size()); Endpoint ep = (Endpoint) service.getEndpoints().iterator().next(); assertNotNull(ep); assertEquals("http://localhost/TestService", ep.getUrl()); assertEquals(3, service.getInHandlers().size()); Handler testHandler = (Handler) service.getInHandlers().get(2); assertTrue(testHandler instanceof TestHandler); assertEquals(testHandler.getAfter().size(),1); assertEquals(testHandler.getBefore().size(),2); assertEquals(service.getOutHandlers().size(),1); assertEquals("value", service.getProperty("myKey")); assertEquals("value1", service.getProperty("myKey1")); service = xfire.getServiceRegistry().getService("EchoWithJustImpl"); assertEquals(EchoImpl.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithBean"); Invoker invoker = service.getInvoker(); assertTrue(invoker instanceof BeanInvoker); assertEquals(Echo.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithBeanNoServiceClass"); invoker = service.getInvoker(); assertTrue(invoker instanceof BeanInvoker); assertEquals(EchoImpl.class, service.getServiceInfo().getServiceClass()); service = xfire.getServiceRegistry().getService("EchoWithSchemas"); ServiceBean serviceBean = (ServiceBean) getBean("EchoWithServiceFactory"); assertTrue(serviceBean.getServiceFactory() instanceof CustomServiceFactory); serviceBean = (ServiceBean) getBean("EchoWithBeanServiceFactory"); assertTrue(serviceBean.getServiceFactory() instanceof CustomServiceFactory); serviceBean = (ServiceBean) getBean("EchoWithInvoker"); assertTrue(serviceBean.getInvoker() instanceof ObjectInvoker); }
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/adapters/MoviesAdapter.java b/SeriesGuide/src/com/battlelancer/seriesguide/adapters/MoviesAdapter.java index e1aeb3b14..4ad625138 100644 --- a/SeriesGuide/src/com/battlelancer/seriesguide/adapters/MoviesAdapter.java +++ b/SeriesGuide/src/com/battlelancer/seriesguide/adapters/MoviesAdapter.java @@ -1,89 +1,94 @@ /* * Copyright 2013 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.battlelancer.seriesguide.adapters; import android.content.Context; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.uwetrottmann.seriesguide.R; import com.uwetrottmann.tmdb.entities.Movie; import java.util.List; /** * Displays movie titles of the given {@link Movie} array. */ public class MoviesAdapter extends ArrayAdapter<Movie> { private static int LAYOUT = R.layout.movie_item; private LayoutInflater mInflater; public MoviesAdapter(Context context) { super(context, LAYOUT); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid // unneccessary calls to findViewById() on each row. ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(LAYOUT, null); holder = new ViewHolder(); holder.title = (TextView) convertView.findViewById(R.id.textViewMovieTitle); holder.date = (TextView) convertView.findViewById(R.id.textViewMovieDate); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // Bind the data efficiently with the holder. Movie movie = getItem(position); holder.title.setText(movie.title); - holder.date.setText(DateUtils.formatDateTime(getContext(), movie.release_date.getTime(), - DateUtils.FORMAT_SHOW_DATE)); + if (movie.release_date != null) { + holder.date.setText(DateUtils.formatDateTime(getContext(), + movie.release_date.getTime(), + DateUtils.FORMAT_SHOW_DATE)); + } else { + holder.date.setText(""); + } return convertView; } public void setData(List<Movie> data) { clear(); if (data != null) { for (Movie item : data) { add(item); } } } static class ViewHolder { TextView title; TextView date; } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid // unneccessary calls to findViewById() on each row. ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(LAYOUT, null); holder = new ViewHolder(); holder.title = (TextView) convertView.findViewById(R.id.textViewMovieTitle); holder.date = (TextView) convertView.findViewById(R.id.textViewMovieDate); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // Bind the data efficiently with the holder. Movie movie = getItem(position); holder.title.setText(movie.title); holder.date.setText(DateUtils.formatDateTime(getContext(), movie.release_date.getTime(), DateUtils.FORMAT_SHOW_DATE)); return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid // unneccessary calls to findViewById() on each row. ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(LAYOUT, null); holder = new ViewHolder(); holder.title = (TextView) convertView.findViewById(R.id.textViewMovieTitle); holder.date = (TextView) convertView.findViewById(R.id.textViewMovieDate); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // Bind the data efficiently with the holder. Movie movie = getItem(position); holder.title.setText(movie.title); if (movie.release_date != null) { holder.date.setText(DateUtils.formatDateTime(getContext(), movie.release_date.getTime(), DateUtils.FORMAT_SHOW_DATE)); } else { holder.date.setText(""); } return convertView; }
diff --git a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/form/fields/radiobuttongroup/internal/RadioButtonGroupGrid.java b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/form/fields/radiobuttongroup/internal/RadioButtonGroupGrid.java index f64db602b7..7f468a488a 100644 --- a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/form/fields/radiobuttongroup/internal/RadioButtonGroupGrid.java +++ b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/form/fields/radiobuttongroup/internal/RadioButtonGroupGrid.java @@ -1,95 +1,95 @@ /******************************************************************************* * Copyright (c) 2010 BSI Business Systems Integration AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipse.scout.rt.client.ui.form.fields.radiobuttongroup.internal; import java.util.ArrayList; import org.eclipse.scout.commons.logger.IScoutLogger; import org.eclipse.scout.commons.logger.ScoutLogManager; import org.eclipse.scout.rt.client.ui.form.fields.GridData; import org.eclipse.scout.rt.client.ui.form.fields.ICompositeField; import org.eclipse.scout.rt.client.ui.form.fields.IFormField; import org.eclipse.scout.rt.client.ui.form.fields.internal.GridDataBuilder; /** * Grid (model) layout of radio button group only visible process-buttons are * used */ public class RadioButtonGroupGrid { private static final IScoutLogger LOG = ScoutLogManager.getLogger(RadioButtonGroupGrid.class); private ICompositeField m_group = null; private IFormField[] m_fields; private int m_gridColumns; private int m_gridRows; public RadioButtonGroupGrid(ICompositeField group) { m_group = group; } public void validate() { // reset m_gridColumns = 0; m_gridRows = 0; ArrayList<IFormField> list = new ArrayList<IFormField>(); // filter for (IFormField f : m_group.getFields()) { if (f.isVisible()) { list.add(f); } else { GridData data = GridDataBuilder.createFromHints(f, 1); f.setGridDataInternal(data); } } m_fields = list.toArray(new IFormField[list.size()]); layoutStatic(); } private void layoutStatic() { GridData parentData = m_group.getGridData(); if (parentData.h <= 0) { LOG.error(m_group.getClass().getName() + " has gridData.h=" + parentData.h + "; expected value>0"); m_gridRows = 1; } else if (m_fields.length <= 0) { - LOG.error(m_group.getClass().getName() + " has fieldCount=" + parentData.h + "; expected value>0"); + LOG.error(m_group.getClass().getName() + " has fieldCount=" + m_fields.length + "; expected value>0"); m_gridRows = 1; } else { m_gridRows = Math.min(parentData.h, m_fields.length); } m_gridColumns = (m_fields.length + m_gridRows - 1) / m_gridRows; int i = 0; for (int r = 0; r < m_gridRows; r++) { for (int c = 0; c < m_gridColumns; c++) { if (i < m_fields.length) { GridData data = GridDataBuilder.createFromHints(m_fields[i], 1); data.x = c; data.y = r; m_fields[i].setGridDataInternal(data); i++; } else { break; } } } } public int getGridColumnCount() { return m_gridColumns; } public int getGridRowCount() { return m_gridRows; } }
true
true
private void layoutStatic() { GridData parentData = m_group.getGridData(); if (parentData.h <= 0) { LOG.error(m_group.getClass().getName() + " has gridData.h=" + parentData.h + "; expected value>0"); m_gridRows = 1; } else if (m_fields.length <= 0) { LOG.error(m_group.getClass().getName() + " has fieldCount=" + parentData.h + "; expected value>0"); m_gridRows = 1; } else { m_gridRows = Math.min(parentData.h, m_fields.length); } m_gridColumns = (m_fields.length + m_gridRows - 1) / m_gridRows; int i = 0; for (int r = 0; r < m_gridRows; r++) { for (int c = 0; c < m_gridColumns; c++) { if (i < m_fields.length) { GridData data = GridDataBuilder.createFromHints(m_fields[i], 1); data.x = c; data.y = r; m_fields[i].setGridDataInternal(data); i++; } else { break; } } } }
private void layoutStatic() { GridData parentData = m_group.getGridData(); if (parentData.h <= 0) { LOG.error(m_group.getClass().getName() + " has gridData.h=" + parentData.h + "; expected value>0"); m_gridRows = 1; } else if (m_fields.length <= 0) { LOG.error(m_group.getClass().getName() + " has fieldCount=" + m_fields.length + "; expected value>0"); m_gridRows = 1; } else { m_gridRows = Math.min(parentData.h, m_fields.length); } m_gridColumns = (m_fields.length + m_gridRows - 1) / m_gridRows; int i = 0; for (int r = 0; r < m_gridRows; r++) { for (int c = 0; c < m_gridColumns; c++) { if (i < m_fields.length) { GridData data = GridDataBuilder.createFromHints(m_fields[i], 1); data.x = c; data.y = r; m_fields[i].setGridDataInternal(data); i++; } else { break; } } } }
diff --git a/src/main/java/com/ai/myplugin/sensor/WaterLevelSensor.java b/src/main/java/com/ai/myplugin/sensor/WaterLevelSensor.java index 25e3a89..3e2a413 100644 --- a/src/main/java/com/ai/myplugin/sensor/WaterLevelSensor.java +++ b/src/main/java/com/ai/myplugin/sensor/WaterLevelSensor.java @@ -1,198 +1,198 @@ package com.ai.myplugin.sensor; import com.ai.bayes.plugins.BNSensorPlugin; import com.ai.bayes.scenario.TestResult; import com.ai.myplugin.util.EmptyTestResult; import com.ai.myplugin.util.Rest; import com.ai.util.resource.TestSessionContext; import net.xeoh.plugins.base.annotations.PluginImplementation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONObject; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * Created by User: veselin * On Date: 21/10/13 */ /* http://www.overstromingsvoorspeller.be/default.aspx?path=NL/Actuele_Info/PluviograafTabel&KL=nl&mode=P <td style="border: 1px solid #dddddd"><a title="Link naar grafieken" href="&#xD;&#xA;default.aspx?path=NL/Kaarten/puntdetail&amp;XMLFileArg=HYD-P05">HYD-P05-R</a></td> <td style="border: 1px solid #dddddd">Neerslag Vinderhoute</td> <td style="border: 1px solid #dddddd">Gentse Kanalen</td> <td style="border: 1px solid #dddddd">1.21 mm</td> <td style="border: 1px solid #dddddd">0.40 mm</td> <td style="border: 1px solid #dddddd">19:45 21/10/2013</td> </tr> */ @PluginImplementation public class WaterLevelSensor implements BNSensorPlugin{ private static final Log log = LogFactory.getLog(WaterLevelSensor.class); public static final String LOCATION = "location"; private String location = null; public static final String DAILY_THRESHOLD = "daily_threshold"; private Integer dailyThreshold = null; public static final String TOTAL_THRESHOLD = "total_threshold"; private Integer totalThreshold = null; private Integer dailyForecastThreshold = null; private Integer totalForecastThreshold = null; @Override public String[] getRequiredProperties() { return new String[]{LOCATION, DAILY_THRESHOLD, TOTAL_THRESHOLD}; } @Override public void setProperty(String s, Object o) { if(LOCATION.equals(s)) location = o.toString(); else if(TOTAL_THRESHOLD.equals(s)) totalThreshold = Integer.parseInt(o.toString()); else if(DAILY_THRESHOLD.equals(s)) dailyThreshold = Integer.parseInt(o.toString()); else throw new RuntimeException("Property "+ s + " not in the required settings"); } @Override public Object getProperty(String s) { if(LOCATION.equals(s)) return location; else if(DAILY_THRESHOLD.equals(s)) return dailyThreshold; else if(TOTAL_THRESHOLD.equals(s)) return totalThreshold; else throw new RuntimeException("Property "+ s + " not in the required settings"); } @Override public String getDescription() { return "Water level"; } @Override public TestResult execute(TestSessionContext testSessionContext) { log.info("execute "+ getName() + ", sensor type:" +this.getClass().getName()); for(String property : getRequiredProperties()){ if(getProperty(property) == null) throw new RuntimeException("Required property "+property + " not defined"); } boolean testSuccess = true; String stringToParse = ""; double total = Double.MAX_VALUE; double daily = Double.MAX_VALUE; double totalForecast = Double.MAX_VALUE; double dailyForecast = Double.MAX_VALUE; String pathURL = "http://www.overstromingsvoorspeller.be/default.aspx?path=NL/Actuele_Info/Neerslagtabellen&XSLTArg_TableID=benedenschelde&XSLTArg_ShowAll=1"; try{ stringToParse = Rest.httpGet(pathURL); log.debug(stringToParse); } catch (Exception e) { testSuccess = false; } if(testSuccess){ int len = stringToParse.indexOf(location); if(len > 0){ String tmp = stringToParse.substring(len); tmp = tmp.replaceAll("#dddddd\">", "|"); StringTokenizer stringTokenizer = new StringTokenizer(tmp, "|"); if(stringTokenizer.countTokens() > 6){ stringTokenizer.nextToken(); stringTokenizer.nextToken(); stringTokenizer.nextToken(); String totalString = stringTokenizer.nextToken(); String dailyString = stringTokenizer.nextToken(); String dailyForecastString = stringTokenizer.nextToken(); String totalForecastString = stringTokenizer.nextToken(); total = Double.parseDouble(totalString.substring(0, totalString.indexOf("mm")).trim()); daily = Double.parseDouble(dailyString.substring(0, dailyString.indexOf("mm")).trim()); - totalForecast = Double.parseDouble(totalForecastString.substring(0, totalString.indexOf("mm")).trim()); - dailyForecast = Double.parseDouble(dailyForecastString.substring(0, dailyString.indexOf("mm")).trim()); + totalForecast = Double.parseDouble(totalForecastString.substring(0, totalForecastString.indexOf("mm")).trim()); + dailyForecast = Double.parseDouble(dailyForecastString.substring(0, dailyForecastString.indexOf("mm")).trim()); log.info("DAILY: "+daily + ", TOTAL:" + total + ", DAILY FORECAST: "+daily + ", TOTAL FORECAST:" + total); } } } if(testSuccess && daily != Double.MAX_VALUE && daily != Double.MAX_VALUE) { String ret = "No Alarm"; if(daily > Integer.parseInt(getProperty(DAILY_THRESHOLD).toString()) || total > Integer.parseInt(getProperty(TOTAL_THRESHOLD).toString())) ret = "Alarm"; final String finalRet = ret; final double finalDaily = daily; final double finalTotal = total; final double finalForecastDaily = dailyForecast; final double finalForecastTotal = totalForecast; return new TestResult() { @Override public boolean isSuccess() { return true; } @Override public String getName() { return "Water level result"; } @Override public String getObserverState() { return finalRet; } @Override public List<Map<String, Number>> getObserverStates() { return null; } @Override public String getRawData() { JSONObject jsonObject = new JSONObject(); jsonObject.put("dailyLevel", new Double(finalDaily)); jsonObject.put("totalLevel", new Double(finalTotal)); jsonObject.put("dailyForecastLevel", new Double(finalForecastDaily)); jsonObject.put("totalForecastLevel", new Double(finalForecastTotal)); return jsonObject.toJSONString(); } }; } else return new EmptyTestResult(); } @Override public String getName() { return "WaterLevelSensor"; } @Override public String[] getSupportedStates() { return new String[] {"No Alarm", "Alarm"}; } @Override public void shutdown(TestSessionContext testSessionContext) { log.debug("Shutdown : " + getName() + ", sensor : "+this.getClass().getName()); } public static void main(String []args){ WaterLevelSensor waterLevelSensor = new WaterLevelSensor(); waterLevelSensor.setProperty(LOCATION, "PDM-438-R"); waterLevelSensor.setProperty(DAILY_THRESHOLD, 15); waterLevelSensor.setProperty(TOTAL_THRESHOLD, 1); TestResult testResult = waterLevelSensor.execute(null); log.info(testResult.getObserverState()); log.info(testResult.getRawData()); } }
true
true
public TestResult execute(TestSessionContext testSessionContext) { log.info("execute "+ getName() + ", sensor type:" +this.getClass().getName()); for(String property : getRequiredProperties()){ if(getProperty(property) == null) throw new RuntimeException("Required property "+property + " not defined"); } boolean testSuccess = true; String stringToParse = ""; double total = Double.MAX_VALUE; double daily = Double.MAX_VALUE; double totalForecast = Double.MAX_VALUE; double dailyForecast = Double.MAX_VALUE; String pathURL = "http://www.overstromingsvoorspeller.be/default.aspx?path=NL/Actuele_Info/Neerslagtabellen&XSLTArg_TableID=benedenschelde&XSLTArg_ShowAll=1"; try{ stringToParse = Rest.httpGet(pathURL); log.debug(stringToParse); } catch (Exception e) { testSuccess = false; } if(testSuccess){ int len = stringToParse.indexOf(location); if(len > 0){ String tmp = stringToParse.substring(len); tmp = tmp.replaceAll("#dddddd\">", "|"); StringTokenizer stringTokenizer = new StringTokenizer(tmp, "|"); if(stringTokenizer.countTokens() > 6){ stringTokenizer.nextToken(); stringTokenizer.nextToken(); stringTokenizer.nextToken(); String totalString = stringTokenizer.nextToken(); String dailyString = stringTokenizer.nextToken(); String dailyForecastString = stringTokenizer.nextToken(); String totalForecastString = stringTokenizer.nextToken(); total = Double.parseDouble(totalString.substring(0, totalString.indexOf("mm")).trim()); daily = Double.parseDouble(dailyString.substring(0, dailyString.indexOf("mm")).trim()); totalForecast = Double.parseDouble(totalForecastString.substring(0, totalString.indexOf("mm")).trim()); dailyForecast = Double.parseDouble(dailyForecastString.substring(0, dailyString.indexOf("mm")).trim()); log.info("DAILY: "+daily + ", TOTAL:" + total + ", DAILY FORECAST: "+daily + ", TOTAL FORECAST:" + total); } } } if(testSuccess && daily != Double.MAX_VALUE && daily != Double.MAX_VALUE) { String ret = "No Alarm"; if(daily > Integer.parseInt(getProperty(DAILY_THRESHOLD).toString()) || total > Integer.parseInt(getProperty(TOTAL_THRESHOLD).toString())) ret = "Alarm"; final String finalRet = ret; final double finalDaily = daily; final double finalTotal = total; final double finalForecastDaily = dailyForecast; final double finalForecastTotal = totalForecast; return new TestResult() { @Override public boolean isSuccess() { return true; } @Override public String getName() { return "Water level result"; } @Override public String getObserverState() { return finalRet; } @Override public List<Map<String, Number>> getObserverStates() { return null; } @Override public String getRawData() { JSONObject jsonObject = new JSONObject(); jsonObject.put("dailyLevel", new Double(finalDaily)); jsonObject.put("totalLevel", new Double(finalTotal)); jsonObject.put("dailyForecastLevel", new Double(finalForecastDaily)); jsonObject.put("totalForecastLevel", new Double(finalForecastTotal)); return jsonObject.toJSONString(); } }; } else return new EmptyTestResult(); }
public TestResult execute(TestSessionContext testSessionContext) { log.info("execute "+ getName() + ", sensor type:" +this.getClass().getName()); for(String property : getRequiredProperties()){ if(getProperty(property) == null) throw new RuntimeException("Required property "+property + " not defined"); } boolean testSuccess = true; String stringToParse = ""; double total = Double.MAX_VALUE; double daily = Double.MAX_VALUE; double totalForecast = Double.MAX_VALUE; double dailyForecast = Double.MAX_VALUE; String pathURL = "http://www.overstromingsvoorspeller.be/default.aspx?path=NL/Actuele_Info/Neerslagtabellen&XSLTArg_TableID=benedenschelde&XSLTArg_ShowAll=1"; try{ stringToParse = Rest.httpGet(pathURL); log.debug(stringToParse); } catch (Exception e) { testSuccess = false; } if(testSuccess){ int len = stringToParse.indexOf(location); if(len > 0){ String tmp = stringToParse.substring(len); tmp = tmp.replaceAll("#dddddd\">", "|"); StringTokenizer stringTokenizer = new StringTokenizer(tmp, "|"); if(stringTokenizer.countTokens() > 6){ stringTokenizer.nextToken(); stringTokenizer.nextToken(); stringTokenizer.nextToken(); String totalString = stringTokenizer.nextToken(); String dailyString = stringTokenizer.nextToken(); String dailyForecastString = stringTokenizer.nextToken(); String totalForecastString = stringTokenizer.nextToken(); total = Double.parseDouble(totalString.substring(0, totalString.indexOf("mm")).trim()); daily = Double.parseDouble(dailyString.substring(0, dailyString.indexOf("mm")).trim()); totalForecast = Double.parseDouble(totalForecastString.substring(0, totalForecastString.indexOf("mm")).trim()); dailyForecast = Double.parseDouble(dailyForecastString.substring(0, dailyForecastString.indexOf("mm")).trim()); log.info("DAILY: "+daily + ", TOTAL:" + total + ", DAILY FORECAST: "+daily + ", TOTAL FORECAST:" + total); } } } if(testSuccess && daily != Double.MAX_VALUE && daily != Double.MAX_VALUE) { String ret = "No Alarm"; if(daily > Integer.parseInt(getProperty(DAILY_THRESHOLD).toString()) || total > Integer.parseInt(getProperty(TOTAL_THRESHOLD).toString())) ret = "Alarm"; final String finalRet = ret; final double finalDaily = daily; final double finalTotal = total; final double finalForecastDaily = dailyForecast; final double finalForecastTotal = totalForecast; return new TestResult() { @Override public boolean isSuccess() { return true; } @Override public String getName() { return "Water level result"; } @Override public String getObserverState() { return finalRet; } @Override public List<Map<String, Number>> getObserverStates() { return null; } @Override public String getRawData() { JSONObject jsonObject = new JSONObject(); jsonObject.put("dailyLevel", new Double(finalDaily)); jsonObject.put("totalLevel", new Double(finalTotal)); jsonObject.put("dailyForecastLevel", new Double(finalForecastDaily)); jsonObject.put("totalForecastLevel", new Double(finalForecastTotal)); return jsonObject.toJSONString(); } }; } else return new EmptyTestResult(); }
diff --git a/src/java/com/eviware/soapui/support/editor/views/xml/source/XmlSourceEditorView.java b/src/java/com/eviware/soapui/support/editor/views/xml/source/XmlSourceEditorView.java index 6cbc28de9..35f21f18f 100644 --- a/src/java/com/eviware/soapui/support/editor/views/xml/source/XmlSourceEditorView.java +++ b/src/java/com/eviware/soapui/support/editor/views/xml/source/XmlSourceEditorView.java @@ -1,920 +1,920 @@ /* * soapUI, copyright (C) 2004-2012 smartbear.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI 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 Lesser General Public License for more details at gnu.org. */ package com.eviware.soapui.support.editor.views.xml.source; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSplitPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.CaretListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.apache.xmlbeans.XmlError; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlOptions; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; import org.fife.ui.rtextarea.SearchContext; import org.fife.ui.rtextarea.SearchEngine; import com.eviware.soapui.SoapUI; import com.eviware.soapui.model.ModelItem; import com.eviware.soapui.model.propertyexpansion.PropertyExpander; import com.eviware.soapui.settings.UISettings; import com.eviware.soapui.support.DocumentListenerAdapter; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.components.JEditorStatusBar.JEditorStatusBarTarget; import com.eviware.soapui.support.components.PreviewCorner; import com.eviware.soapui.support.editor.EditorLocation; import com.eviware.soapui.support.editor.views.AbstractXmlEditorView; import com.eviware.soapui.support.editor.xml.XmlDocument; import com.eviware.soapui.support.editor.xml.XmlEditor; import com.eviware.soapui.support.editor.xml.XmlLocation; import com.eviware.soapui.support.editor.xml.support.ValidationError; import com.eviware.soapui.support.propertyexpansion.PropertyExpansionPopupListener; import com.eviware.soapui.support.swing.JTextComponentPopupMenu; import com.eviware.soapui.support.swing.SoapUISplitPaneUI; import com.eviware.soapui.support.xml.XmlUtils; import com.eviware.soapui.support.xml.actions.EnableLineNumbersAction; import com.eviware.soapui.support.xml.actions.FormatXmlAction; import com.eviware.soapui.support.xml.actions.GoToLineAction; import com.eviware.soapui.support.xml.actions.InsertBase64FileTextAreaAction; import com.eviware.soapui.support.xml.actions.LoadXmlTextAreaAction; import com.eviware.soapui.support.xml.actions.SaveXmlTextAreaAction; import com.jgoodies.forms.builder.ButtonBarBuilder; /** * Default "XML" source editor view in soapUI * * @author ole.matzura */ public class XmlSourceEditorView<T extends ModelItem> extends AbstractXmlEditorView<XmlDocument> { private RSyntaxTextArea editArea; private RTextScrollPane editorScrollPane; private ValidateMessageXmlAction validateXmlAction; private JSplitPane splitter; private JScrollPane errorScrollPane; private DefaultListModel errorListModel; private boolean updating; public boolean isLocating; private JPopupMenu inputPopup; private PreviewCorner previewCorner; private T modelItem; private EnableLineNumbersAction enableLineNumbersAction; private GoToLineAction goToLineAction; private SaveXmlTextAreaAction saveXmlTextAreaAction; // Read only views don't need these private FormatXmlAction formatXmlAction; private LoadXmlTextAreaAction loadXmlTextAreaAction; private InsertBase64FileTextAreaAction insertBase64FileTextAreaAction; private FindAndReplaceDialogView findAndReplaceDialog; private final boolean readOnly; public XmlSourceEditorView( XmlEditor<XmlDocument> xmlEditor, T modelItem, boolean readOnly ) { super( "XML", xmlEditor, XmlSourceEditorViewFactory.VIEW_ID ); this.modelItem = modelItem; this.readOnly = readOnly; } protected void buildUI() { editArea = new RSyntaxTextArea( 20, 60 ); editArea.setSyntaxEditingStyle( SyntaxConstants.SYNTAX_STYLE_XML ); editArea.setFont( UISupport.getEditorFont() ); editArea.setCodeFoldingEnabled( true ); editArea.setAntiAliasingEnabled( true ); editArea.setMinimumSize( new Dimension( 50, 50 ) ); editArea.setCaretPosition( 0 ); editArea.setEnabled( !readOnly ); editArea.setEditable( !readOnly ); editArea.setBorder( BorderFactory.createMatteBorder( 0, 2, 0, 0, Color.WHITE ) ); errorListModel = new DefaultListModel(); JList list = new JList( errorListModel ); list.addMouseListener( new ValidationListMouseAdapter( list, editArea ) ); errorScrollPane = new JScrollPane( list ); errorScrollPane.setVisible( false ); splitter = new JSplitPane( JSplitPane.VERTICAL_SPLIT ) { public void requestFocus() { SwingUtilities.invokeLater( new Runnable() { public void run() { editArea.requestFocusInWindow(); } } ); } public boolean hasFocus() { return editArea.hasFocus(); } }; splitter.setUI( new SoapUISplitPaneUI() ); splitter.setDividerSize( 0 ); splitter.setOneTouchExpandable( true ); editArea.getDocument().addDocumentListener( new DocumentListenerAdapter() { public void update( Document document ) { if( !updating && getDocument() != null ) { updating = true; getDocument().setXml( editArea.getText() ); updating = false; } } } ); JPanel p = new JPanel( new BorderLayout() ); editorScrollPane = new RTextScrollPane( editArea ); JTextComponentPopupMenu.add( editArea ); buildPopup( editArea.getPopupMenu(), editArea ); if( UISupport.isMac() ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta V" ), validateXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta S" ), saveXmlTextAreaAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control L" ), enableLineNumbersAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control meta L" ), goToLineAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta F" ), findAndReplaceDialog ); + editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); if( !readOnly ) { - editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta L" ), loadXmlTextAreaAction ); } } else { editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt V" ), validateXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl S" ), saveXmlTextAreaAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt L" ), enableLineNumbersAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control alt L" ), goToLineAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl F" ), findAndReplaceDialog ); + editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); if( !readOnly ) { - editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl L" ), loadXmlTextAreaAction ); } } editorScrollPane.setLineNumbersEnabled( SoapUI.getSettings().getBoolean( UISettings.SHOW_XML_LINE_NUMBERS ) ); editorScrollPane.setFoldIndicatorEnabled( true ); p.add( editorScrollPane, BorderLayout.CENTER ); splitter.setTopComponent( editorScrollPane ); splitter.setBottomComponent( errorScrollPane ); splitter.setDividerLocation( 1.0 ); splitter.setBorder( null ); previewCorner = UISupport.addPreviewCorner( getEditorScrollPane(), true ); if( !readOnly ) { PropertyExpansionPopupListener.enable( editArea, modelItem ); } } public JScrollPane getEditorScrollPane() { return editorScrollPane; } public T getModelItem() { return modelItem; } protected void buildPopup( JPopupMenu inputPopup, RSyntaxTextArea editArea ) { this.inputPopup = inputPopup; validateXmlAction = new ValidateMessageXmlAction(); saveXmlTextAreaAction = new SaveXmlTextAreaAction( editArea, "Save" ); enableLineNumbersAction = new EnableLineNumbersAction( editorScrollPane, "Toggle Line Numbers" ); goToLineAction = new GoToLineAction( editArea, "Go To Line" ); findAndReplaceDialog = new FindAndReplaceDialogView( "Find / Replace" ); if( !readOnly ) { loadXmlTextAreaAction = new LoadXmlTextAreaAction( editArea, "Load" ); insertBase64FileTextAreaAction = new InsertBase64FileTextAreaAction( editArea, "Insert File as Base64" ); } int cnt = inputPopup.getComponentCount(); for( int i = cnt - 1; i >= 0; i-- ) { if( inputPopup.getComponent( i ) instanceof JSeparator ) { inputPopup.remove( inputPopup.getComponent( i ) ); } } inputPopup.insert( validateXmlAction, 0 ); formatXmlAction = new FormatXmlAction( editArea ); inputPopup.insert( formatXmlAction, 1 ); inputPopup.addSeparator(); inputPopup.add( findAndReplaceDialog ); inputPopup.addSeparator(); inputPopup.add( goToLineAction ); inputPopup.add( enableLineNumbersAction ); inputPopup.addSeparator(); inputPopup.add( saveXmlTextAreaAction ); if( !readOnly ) { inputPopup.add( loadXmlTextAreaAction ); inputPopup.add( insertBase64FileTextAreaAction ); } } @Override public void release() { super.release(); inputPopup.removeAll(); previewCorner.release(); modelItem = null; } private final class FindAndReplaceDialogView extends AbstractAction { private JDialog dialog; private JCheckBox caseCheck; private JRadioButton allButton; private JRadioButton selectedLinesButton; private JRadioButton forwardButton; private JRadioButton backwardButton; private JCheckBox wholeWordCheck; private JButton findButton; private JButton replaceButton; private JButton replaceAllButton; private JComboBox findCombo; private JComboBox replaceCombo; private JCheckBox wrapCheck; private final String title; public FindAndReplaceDialogView( String title ) { super( title ); this.title = title; if( UISupport.isMac() ) putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "meta F" ) ); else putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "ctrl F" ) ); } @Override public void actionPerformed( ActionEvent arg0 ) { show(); } public void show() { if( dialog == null ) buildDialog(); editArea.requestFocusInWindow(); replaceCombo.setEnabled( !readOnly ); replaceAllButton.setEnabled( !readOnly ); replaceButton.setEnabled( !readOnly ); UISupport.showDialog( dialog ); findCombo.getEditor().selectAll(); findCombo.requestFocus(); } private void buildDialog() { Window window = SwingUtilities.windowForComponent( editArea ); dialog = new JDialog( window, title ); dialog.setModal( false ); JPanel panel = new JPanel( new BorderLayout() ); findCombo = new JComboBox(); findCombo.setEditable( true ); replaceCombo = new JComboBox(); replaceCombo.setEditable( !readOnly ); // create inputs GridLayout gridLayout = new GridLayout( 2, 2 ); gridLayout.setVgap( 5 ); JPanel inputPanel = new JPanel( gridLayout ); inputPanel.add( new JLabel( "Find:" ) ); inputPanel.add( findCombo ); inputPanel.add( new JLabel( "Replace with:" ) ); inputPanel.add( replaceCombo ); inputPanel.setBorder( BorderFactory.createEmptyBorder( 8, 8, 8, 8 ) ); // create direction panel ButtonGroup directionGroup = new ButtonGroup(); forwardButton = new JRadioButton( "Forward", true ); forwardButton.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); directionGroup.add( forwardButton ); backwardButton = new JRadioButton( "Backward" ); backwardButton.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); directionGroup.add( backwardButton ); JPanel directionPanel = new JPanel( new GridLayout( 2, 1 ) ); directionPanel.add( forwardButton ); directionPanel.add( backwardButton ); directionPanel.setBorder( BorderFactory.createTitledBorder( "Direction" ) ); // create scope panel ButtonGroup scopeGroup = new ButtonGroup(); allButton = new JRadioButton( "All", true ); allButton.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); selectedLinesButton = new JRadioButton( "Selected Lines" ); selectedLinesButton.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); scopeGroup.add( allButton ); scopeGroup.add( selectedLinesButton ); JPanel scopePanel = new JPanel( new GridLayout( 2, 1 ) ); scopePanel.add( allButton ); scopePanel.add( selectedLinesButton ); scopePanel.setBorder( BorderFactory.createTitledBorder( "Scope" ) ); // create options caseCheck = new JCheckBox( "Case Sensitive" ); caseCheck.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); wholeWordCheck = new JCheckBox( "Whole Word" ); wholeWordCheck.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); wrapCheck = new JCheckBox( "Wrap Search" ); wrapCheck.setBorder( BorderFactory.createEmptyBorder( 3, 3, 3, 3 ) ); JPanel optionsPanel = new JPanel( new GridLayout( 3, 1 ) ); optionsPanel.add( caseCheck ); optionsPanel.add( wholeWordCheck ); optionsPanel.add( wrapCheck ); optionsPanel.setBorder( BorderFactory.createTitledBorder( "Options" ) ); // create panel with options JPanel options = new JPanel( new GridLayout( 1, 2 ) ); JPanel radios = new JPanel( new GridLayout( 2, 1 ) ); radios.add( directionPanel ); radios.add( scopePanel ); options.add( optionsPanel ); options.add( radios ); options.setBorder( BorderFactory.createEmptyBorder( 0, 8, 0, 8 ) ); // create buttons ButtonBarBuilder builder = new ButtonBarBuilder(); findButton = new JButton( new FindAction( findCombo ) ); builder.addFixed( findButton ); builder.addRelatedGap(); replaceButton = new JButton( new ReplaceAction() ); builder.addFixed( replaceButton ); builder.addRelatedGap(); replaceAllButton = new JButton( new ReplaceAllAction() ); builder.addFixed( replaceAllButton ); builder.addUnrelatedGap(); builder.addFixed( new JButton( new CloseAction( dialog ) ) ); builder.setBorder( BorderFactory.createEmptyBorder( 8, 8, 8, 8 ) ); // tie it up! panel.add( inputPanel, BorderLayout.NORTH ); panel.add( options, BorderLayout.CENTER ); panel.add( builder.getPanel(), BorderLayout.SOUTH ); dialog.getContentPane().add( panel ); dialog.pack(); UISupport.initDialogActions( dialog, null, findButton ); } protected SearchContext createSearchAndReplaceContext() { if( findCombo.getSelectedItem() == null ) { return null; } if( replaceCombo.getSelectedItem() == null ) { return null; } String searchExpression = findCombo.getSelectedItem().toString(); String replacement = replaceCombo.getSelectedItem().toString(); SearchContext context = new SearchContext(); context.setSearchFor( searchExpression ); context.setReplaceWith( replacement ); context.setRegularExpression( false ); context.setMatchCase( caseCheck.isEnabled() ); context.setSearchForward( forwardButton.isSelected() ); context.setWholeWord( false ); return context; } protected SearchContext createSearchContext() { if( findCombo.getSelectedItem() == null ) { return null; } String searchExpression = findCombo.getSelectedItem().toString(); SearchContext context = new SearchContext(); context.setSearchFor( searchExpression ); context.setRegularExpression( false ); context.setSearchForward( forwardButton.isSelected() ); context.setMatchCase( caseCheck.isEnabled() ); context.setWholeWord( false ); return context; } private class FindAction extends AbstractAction { public FindAction( JComboBox findCombo ) { super( "Find/Find Next" ); } @Override public void actionPerformed( ActionEvent e ) { SearchContext context = createSearchContext(); if( context == null ) { return; } boolean found = SearchEngine.find( editArea, context ); if( !found ) { UISupport.showErrorMessage( "String [" + context.getSearchFor() + "] not found" ); } } } private class ReplaceAction extends AbstractAction { public ReplaceAction() { super( "Replace/Replace Next" ); } @Override public void actionPerformed( ActionEvent e ) { SearchContext context = createSearchAndReplaceContext(); if( context == null ) { return; } boolean found = SearchEngine.replace( editArea, context ); if( !found ) { UISupport.showErrorMessage( "String [" + context.getSearchFor() + "] not found" ); } } } private class ReplaceAllAction extends AbstractAction { public ReplaceAllAction() { super( "Replace All" ); } @Override public void actionPerformed( ActionEvent e ) { SearchContext context = createSearchAndReplaceContext(); if( context == null ) { return; } int replaceCount = SearchEngine.replaceAll( editArea, context ); if( replaceCount <= 0 ) { UISupport.showErrorMessage( "String [" + context.getSearchFor() + "] not found" ); } } } private class CloseAction extends AbstractAction { final JDialog dialog; public CloseAction( JDialog d ) { super( "Close" ); dialog = d; } public void actionPerformed( ActionEvent e ) { dialog.setVisible( false ); } } } // private final class EnableLineNumbersAction extends AbstractAction // { // EnableLineNumbersAction( String title ) // { // super( title ); // if( UISupport.isMac() ) // { // putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "ctrl L" ) ); // } // else // { // putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "ctrl alt L" ) ); // } // } // // @Override // public void actionPerformed( ActionEvent e ) // { // editorScrollPane.setLineNumbersEnabled( !editorScrollPane.getLineNumbersEnabled() ); // } // // } private final static class ValidationListMouseAdapter extends MouseAdapter { private final JList list; private final RSyntaxTextArea textArea; public ValidationListMouseAdapter( JList list, RSyntaxTextArea editArea ) { this.list = list; this.textArea = editArea; } public void mouseClicked( MouseEvent e ) { if( e.getClickCount() < 2 ) return; int ix = list.getSelectedIndex(); if( ix == -1 ) return; Object obj = list.getModel().getElementAt( ix ); if( obj instanceof ValidationError ) { ValidationError error = ( ValidationError )obj; if( error.getLineNumber() >= 0 ) { try { textArea.setCaretPosition( textArea.getLineStartOffset( error.getLineNumber() - 1 ) ); } catch( BadLocationException e1 ) { SoapUI.logError( e1, "Unable to set the caret position. This is most likely a bug." ); } textArea.requestFocus(); } else Toolkit.getDefaultToolkit().beep(); } else Toolkit.getDefaultToolkit().beep(); } } public RSyntaxTextArea getInputArea() { getComponent(); return editArea; } public static class JEditorStatusBarTargetProxy implements JEditorStatusBarTarget { private final RSyntaxTextArea textArea; public JEditorStatusBarTargetProxy( RSyntaxTextArea area ) { textArea = area; } @Override public void addCaretListener( CaretListener listener ) { textArea.addCaretListener( listener ); } @Override public int getCaretPosition() { return textArea.getCaretPosition(); } @Override public void removeCaretListener( CaretListener listener ) { textArea.removeCaretListener( listener ); } @Override public int getLineStartOffset( int line ) throws Exception { return textArea.getLineStartOffset( line ); } @Override public int getLineOfOffset( int offset ) throws Exception { return textArea.getLineOfOffset( offset ); } } public void setEditable( boolean enabled ) { getComponent(); editArea.setEditable( enabled ); } protected ValidationError[] validateXml( String xml ) { try { XmlUtils.createXmlObject( xml, new XmlOptions().setLoadLineNumbers() ); } catch( XmlException e ) { List<ValidationError> result = new ArrayList<ValidationError>(); if( e.getErrors() != null ) { for( Object error : e.getErrors() ) { if( error instanceof XmlError ) result.add( new com.eviware.soapui.model.testsuite.AssertionError( ( XmlError )error ) ); else result.add( new com.eviware.soapui.model.testsuite.AssertionError( error.toString() ) ); } } if( result.isEmpty() ) result.add( new com.eviware.soapui.model.testsuite.AssertionError( e.toString() ) ); return result.toArray( new ValidationError[result.size()] ); } return null; } public class ValidateMessageXmlAction extends AbstractAction { public ValidateMessageXmlAction() { super( "Validate" ); if( UISupport.isMac() ) { putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "shift meta V" ) ); } else { putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "alt V" ) ); } } public void actionPerformed( ActionEvent e ) { if( validate() ) UISupport.showInfoMessage( "Validation OK" ); } } public boolean activate( XmlLocation location ) { super.activate( location ); if( location != null ) setLocation( location ); editArea.requestFocus(); return true; } public JComponent getComponent() { if( splitter == null ) buildUI(); return splitter; } public XmlLocation getEditorLocation() { return new XmlLocation( getCurrentLine() + 1, getCurrentColumn() ); } public void setLocation( XmlLocation location ) { int line = location.getLine() - 1; if( location != null && line >= 0 ) { try { int caretLine = editArea.getCaretLineNumber(); int offset = editArea.getLineStartOffset( line ); editArea.setCaretPosition( offset + location.getColumn() ); int scrollLine = line + ( line > caretLine ? 3 : -3 ); if( scrollLine >= editArea.getLineCount() ) scrollLine = editArea.getLineCount() - 1; else if( scrollLine < 0 ) scrollLine = 0; editArea.scrollRectToVisible( new Rectangle( scrollLine, location.getColumn() ) ); } catch( RuntimeException e ) { } catch( BadLocationException e ) { SoapUI.logError( e, "Unable to set the location in the XML document." ); } } } public int getCurrentLine() { if( editArea == null ) return -1; return editArea.getCaretLineNumber(); } public int getCurrentColumn() { if( editArea == null ) return -1; try { int pos = editArea.getCaretPosition(); int line = editArea.getLineOfOffset( pos ); return pos - editArea.getLineStartOffset( line ); } catch( BadLocationException e ) { SoapUI.logError( e, "Unable to get the current column. " ); return -1; } } public String getText() { if( editArea == null ) return null; return editArea.getText(); } public boolean validate() { ValidationError[] errors = validateXml( PropertyExpander.expandProperties( getModelItem(), editArea.getText() ) ); errorListModel.clear(); if( errors == null || errors.length == 0 ) { splitter.setDividerLocation( 1.0 ); splitter.setDividerSize( 0 ); errorScrollPane.setVisible( false ); return true; } else { Toolkit.getDefaultToolkit().beep(); for( int c = 0; c < errors.length; c++ ) { errorListModel.addElement( errors[c] ); } errorScrollPane.setVisible( true ); splitter.setDividerLocation( 0.8 ); splitter.setDividerSize( 10 ); return false; } } public void setXml( String xml ) { if( !updating ) { updating = true; if( xml == null ) { editArea.setText( "" ); editArea.setEnabled( false ); } else { int caretPosition = editArea.getCaretPosition(); editArea.setEnabled( true ); editArea.setText( xml ); editArea.setCaretPosition( caretPosition < xml.length() ? caretPosition : 0 ); } updating = false; } } public boolean saveDocument( boolean validate ) { return validate ? validate() : true; } public void locationChanged( EditorLocation<XmlDocument> location ) { isLocating = true; setLocation( location ); isLocating = false; } public JPopupMenu getEditorPopup() { return editArea.getPopupMenu(); } public boolean hasFocus() { return editArea.hasFocus(); } public boolean isInspectable() { return true; } public ValidateMessageXmlAction getValidateXmlAction() { return validateXmlAction; } }
false
true
protected void buildUI() { editArea = new RSyntaxTextArea( 20, 60 ); editArea.setSyntaxEditingStyle( SyntaxConstants.SYNTAX_STYLE_XML ); editArea.setFont( UISupport.getEditorFont() ); editArea.setCodeFoldingEnabled( true ); editArea.setAntiAliasingEnabled( true ); editArea.setMinimumSize( new Dimension( 50, 50 ) ); editArea.setCaretPosition( 0 ); editArea.setEnabled( !readOnly ); editArea.setEditable( !readOnly ); editArea.setBorder( BorderFactory.createMatteBorder( 0, 2, 0, 0, Color.WHITE ) ); errorListModel = new DefaultListModel(); JList list = new JList( errorListModel ); list.addMouseListener( new ValidationListMouseAdapter( list, editArea ) ); errorScrollPane = new JScrollPane( list ); errorScrollPane.setVisible( false ); splitter = new JSplitPane( JSplitPane.VERTICAL_SPLIT ) { public void requestFocus() { SwingUtilities.invokeLater( new Runnable() { public void run() { editArea.requestFocusInWindow(); } } ); } public boolean hasFocus() { return editArea.hasFocus(); } }; splitter.setUI( new SoapUISplitPaneUI() ); splitter.setDividerSize( 0 ); splitter.setOneTouchExpandable( true ); editArea.getDocument().addDocumentListener( new DocumentListenerAdapter() { public void update( Document document ) { if( !updating && getDocument() != null ) { updating = true; getDocument().setXml( editArea.getText() ); updating = false; } } } ); JPanel p = new JPanel( new BorderLayout() ); editorScrollPane = new RTextScrollPane( editArea ); JTextComponentPopupMenu.add( editArea ); buildPopup( editArea.getPopupMenu(), editArea ); if( UISupport.isMac() ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta V" ), validateXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta S" ), saveXmlTextAreaAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control L" ), enableLineNumbersAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control meta L" ), goToLineAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta F" ), findAndReplaceDialog ); if( !readOnly ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta L" ), loadXmlTextAreaAction ); } } else { editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt V" ), validateXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl S" ), saveXmlTextAreaAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt L" ), enableLineNumbersAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control alt L" ), goToLineAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl F" ), findAndReplaceDialog ); if( !readOnly ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl L" ), loadXmlTextAreaAction ); } } editorScrollPane.setLineNumbersEnabled( SoapUI.getSettings().getBoolean( UISettings.SHOW_XML_LINE_NUMBERS ) ); editorScrollPane.setFoldIndicatorEnabled( true ); p.add( editorScrollPane, BorderLayout.CENTER ); splitter.setTopComponent( editorScrollPane ); splitter.setBottomComponent( errorScrollPane ); splitter.setDividerLocation( 1.0 ); splitter.setBorder( null ); previewCorner = UISupport.addPreviewCorner( getEditorScrollPane(), true ); if( !readOnly ) { PropertyExpansionPopupListener.enable( editArea, modelItem ); } }
protected void buildUI() { editArea = new RSyntaxTextArea( 20, 60 ); editArea.setSyntaxEditingStyle( SyntaxConstants.SYNTAX_STYLE_XML ); editArea.setFont( UISupport.getEditorFont() ); editArea.setCodeFoldingEnabled( true ); editArea.setAntiAliasingEnabled( true ); editArea.setMinimumSize( new Dimension( 50, 50 ) ); editArea.setCaretPosition( 0 ); editArea.setEnabled( !readOnly ); editArea.setEditable( !readOnly ); editArea.setBorder( BorderFactory.createMatteBorder( 0, 2, 0, 0, Color.WHITE ) ); errorListModel = new DefaultListModel(); JList list = new JList( errorListModel ); list.addMouseListener( new ValidationListMouseAdapter( list, editArea ) ); errorScrollPane = new JScrollPane( list ); errorScrollPane.setVisible( false ); splitter = new JSplitPane( JSplitPane.VERTICAL_SPLIT ) { public void requestFocus() { SwingUtilities.invokeLater( new Runnable() { public void run() { editArea.requestFocusInWindow(); } } ); } public boolean hasFocus() { return editArea.hasFocus(); } }; splitter.setUI( new SoapUISplitPaneUI() ); splitter.setDividerSize( 0 ); splitter.setOneTouchExpandable( true ); editArea.getDocument().addDocumentListener( new DocumentListenerAdapter() { public void update( Document document ) { if( !updating && getDocument() != null ) { updating = true; getDocument().setXml( editArea.getText() ); updating = false; } } } ); JPanel p = new JPanel( new BorderLayout() ); editorScrollPane = new RTextScrollPane( editArea ); JTextComponentPopupMenu.add( editArea ); buildPopup( editArea.getPopupMenu(), editArea ); if( UISupport.isMac() ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta V" ), validateXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta S" ), saveXmlTextAreaAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control L" ), enableLineNumbersAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control meta L" ), goToLineAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta F" ), findAndReplaceDialog ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); if( !readOnly ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "meta L" ), loadXmlTextAreaAction ); } } else { editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt V" ), validateXmlAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl S" ), saveXmlTextAreaAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt L" ), enableLineNumbersAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "control alt L" ), goToLineAction ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl F" ), findAndReplaceDialog ); editArea.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); if( !readOnly ) { editArea.getInputMap().put( KeyStroke.getKeyStroke( "ctrl L" ), loadXmlTextAreaAction ); } } editorScrollPane.setLineNumbersEnabled( SoapUI.getSettings().getBoolean( UISettings.SHOW_XML_LINE_NUMBERS ) ); editorScrollPane.setFoldIndicatorEnabled( true ); p.add( editorScrollPane, BorderLayout.CENTER ); splitter.setTopComponent( editorScrollPane ); splitter.setBottomComponent( errorScrollPane ); splitter.setDividerLocation( 1.0 ); splitter.setBorder( null ); previewCorner = UISupport.addPreviewCorner( getEditorScrollPane(), true ); if( !readOnly ) { PropertyExpansionPopupListener.enable( editArea, modelItem ); } }
diff --git a/src/com/jmex/effects/water/WaterRenderPass.java b/src/com/jmex/effects/water/WaterRenderPass.java index 73cf933c0..5810f6096 100755 --- a/src/com/jmex/effects/water/WaterRenderPass.java +++ b/src/com/jmex/effects/water/WaterRenderPass.java @@ -1,616 +1,614 @@ /* * Copyright (c) 2003-2006 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jmex.effects.water; import java.util.logging.Level; import org.lwjgl.opengl.OpenGLException; import org.lwjgl.opengl.Util; import com.jme.image.Texture; import com.jme.math.FastMath; import com.jme.math.Plane; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.renderer.TextureRenderer; import com.jme.renderer.pass.Pass; import com.jme.scene.Node; import com.jme.scene.SceneElement; import com.jme.scene.Spatial; import com.jme.scene.state.AlphaState; import com.jme.scene.state.ClipState; import com.jme.scene.state.CullState; import com.jme.scene.state.GLSLShaderObjectsState; import com.jme.scene.state.LightState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; import com.jme.util.LoggingSystem; import com.jme.util.TextureManager; /** * <code>WaterRenderPass</code> * Water effect pass. * * @author Rikard Herlitz (MrCoder) */ public class WaterRenderPass extends Pass { private Camera cam; private LightState lightState; private float tpf; private TextureRenderer tRenderer; private Texture textureReflect; private Texture textureRefract; private Texture textureDepth; private Node renderNode; private Node skyBox; private GLSLShaderObjectsState waterShader; private CullState cullBackFace; private TextureState ts; private AlphaState as1; private ClipState clipState; private Plane waterPlane; private Vector3f tangent; private Vector3f binormal; private float clipBias; private ColorRGBA waterColorStart; private ColorRGBA waterColorEnd; private float heightFalloffStart; private float heightFalloffSpeed; private float waterMaxAmplitude; private float speedReflection; private float speedRefraction; private boolean aboveWater; private float normalTranslation = 0.0f; private float refractionTranslation = 0.0f; private boolean supported = true; private boolean useProjectedShader = false; private boolean useRefraction = false; private final String simpleShaderStr = "com/jmex/effects/water/data/flatwatershader"; private final String simpleShaderRefractionStr = "com/jmex/effects/water/data/flatwatershader_refraction"; private final String projectedShaderStr = "com/jmex/effects/water/data/projectedwatershader"; private final String projectedShaderRefractionStr = "com/jmex/effects/water/data/projectedwatershader_refraction"; private String currentShaderStr; public void resetParameters() { waterPlane = new Plane( new Vector3f( 0.0f, 1.0f, 0.0f ), 0.0f ); tangent = new Vector3f( 1.0f, 0.0f, 0.0f ); binormal = new Vector3f( 0.0f, 0.0f, 1.0f ); waterMaxAmplitude = 0.0f; clipBias = 0.0f; waterColorStart = new ColorRGBA( 0.0f, 0.0f, 0.1f, 1.0f ); waterColorEnd = new ColorRGBA( 0.0f, 0.3f, 0.1f, 1.0f ); heightFalloffStart = 300.0f; heightFalloffSpeed = 500.0f; speedReflection = 0.1f; speedRefraction = -0.05f; } /** * Release pbuffers in TextureRenderer's. Preferably called from user cleanup method. */ public void cleanup() { if( isSupported() ) tRenderer.cleanup(); } public boolean isSupported() { return supported; } /** * Creates a new WaterRenderPass * * @param cam main rendercam to use for reflection settings etc * @param renderScale how many times smaller the reflection/refraction textures should be compared to the main display * @param useProjectedShader true - use the projected setup for variable height water meshes, false - use the flast shader setup * @param useRefraction enable/disable rendering of refraction textures */ public WaterRenderPass( Camera cam, int renderScale, boolean useProjectedShader, boolean useRefraction ) { this.cam = cam; this.useProjectedShader = useProjectedShader; this.useRefraction = useRefraction; if( useRefraction && useProjectedShader && TextureState.getNumberOfFragmentUnits() < 6 || useRefraction && TextureState.getNumberOfFragmentUnits() < 5 ) { useRefraction = false; LoggingSystem.getLogger().log( Level.INFO, "Not enough textureunits, falling back to non refraction water" ); } resetParameters(); DisplaySystem display = DisplaySystem.getDisplaySystem(); waterShader = display.getRenderer().createGLSLShaderObjectsState(); if( !waterShader.isSupported() ) { supported = false; } else { } cullBackFace = display.getRenderer().createCullState(); cullBackFace.setEnabled( true ); cullBackFace.setCullMode( CullState.CS_NONE ); clipState = display.getRenderer().createClipState(); if( isSupported() ) { tRenderer = display.createTextureRenderer( display.getWidth() / renderScale, display.getHeight() / renderScale, false, true, false, false, TextureRenderer.RENDER_TEXTURE_2D, 0 ); if( tRenderer.isSupported() ) { tRenderer.setBackgroundColor( new ColorRGBA( 0.0f, 0.0f, 0.0f, 1.0f ) ); tRenderer.getCamera().setFrustum( cam.getFrustumNear(), cam.getFrustumFar(), cam.getFrustumLeft(), cam.getFrustumRight(), cam.getFrustumTop(), cam.getFrustumBottom() ); tRenderer.forceCopy( true ); textureReflect = new Texture(); textureReflect.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureReflect.setFilter( Texture.FM_LINEAR ); textureReflect.setScale( new Vector3f( -1.0f, 1.0f, 1.0f ) ); textureReflect.setTranslation( new Vector3f( 1.0f, 0.0f, 0.0f ) ); tRenderer.setupTexture( textureReflect ); if( useRefraction ) { textureRefract = new Texture(); textureRefract.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureRefract.setFilter( Texture.FM_LINEAR ); tRenderer.setupTexture( textureRefract ); textureDepth = new Texture(); textureDepth.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureDepth.setFilter( Texture.FM_NEAREST ); textureDepth.setRTTSource( Texture.RTT_SOURCE_DEPTH ); tRenderer.setupTexture( textureDepth ); } ts = display.getRenderer().createTextureState(); ts.setEnabled( true ); Texture t1 = TextureManager.loadTexture( -// WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/normalmap3.dds" ), - WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/normalmap.png" ), -// WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/fisk.png" ), + WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/normalmap3.dds" ), Texture.MM_LINEAR_LINEAR, - Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false -// Texture.FM_NEAREST +// Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false + Texture.FM_LINEAR ); ts.setTexture( t1, 0 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); ts.setTexture( textureReflect, 1 ); t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/dudvmap.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false ); ts.setTexture( t1, 2 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); if( useRefraction ) { ts.setTexture( textureRefract, 3 ); ts.setTexture( textureDepth, 4 ); } if( useProjectedShader ) { t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/oceanfoam.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR ); if( useRefraction ) { ts.setTexture( t1, 5 ); } else { ts.setTexture( t1, 3 ); } t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); } clipState.setEnabled( true ); clipState.setEnableClipPlane( ClipState.CLIP_PLANE0, true ); if( useProjectedShader ) { if( useRefraction ) { currentShaderStr = projectedShaderRefractionStr; } else { currentShaderStr = projectedShaderStr; } } else { if( useRefraction ) { currentShaderStr = simpleShaderRefractionStr; } else { currentShaderStr = simpleShaderStr; } } waterShader.load( WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".vert" ), WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".frag" ) ); waterShader.setEnabled( true ); } else { supported = false; } } if( !isSupported() ) { ts = display.getRenderer().createTextureState(); ts.setEnabled( true ); Texture t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/water2.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR ); ts.setTexture( t1, 0 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); as1 = display.getRenderer().createAlphaState(); as1.setBlendEnabled( true ); as1.setSrcFunction( AlphaState.SB_SRC_ALPHA ); as1.setDstFunction( AlphaState.DB_ONE_MINUS_SRC_ALPHA ); as1.setEnabled( true ); } } @Override protected void doUpdate( float tpf ) { super.doUpdate( tpf ); this.tpf = tpf; } public void doRender( Renderer r ) { normalTranslation += speedReflection * tpf; refractionTranslation += speedRefraction * tpf; float camWaterDist = waterPlane.pseudoDistance( cam.getLocation() ); aboveWater = camWaterDist >= 0; if( isSupported() ) { waterShader.clearUniforms(); waterShader.setUniform( "tangent", tangent.x, tangent.y, tangent.z ); waterShader.setUniform( "binormal", binormal.x, binormal.y, binormal.z ); waterShader.setUniform( "normalMap", 0 ); waterShader.setUniform( "reflection", 1 ); waterShader.setUniform( "dudvMap", 2 ); if( useRefraction ) { waterShader.setUniform( "refraction", 3 ); waterShader.setUniform( "depthMap", 4 ); } waterShader.setUniform( "waterColor", waterColorStart.r, waterColorStart.g, waterColorStart.b, waterColorStart.a ); waterShader.setUniform( "waterColorEnd", waterColorEnd.r, waterColorEnd.g, waterColorEnd.b, waterColorEnd.a ); waterShader.setUniform( "normalTranslation", normalTranslation ); waterShader.setUniform( "refractionTranslation", refractionTranslation ); waterShader.setUniform( "abovewater", aboveWater ? 1 : 0 ); if( useProjectedShader ) { waterShader.setUniform( "cameraPos", cam.getLocation().x, cam.getLocation().y, cam.getLocation().z ); if( useRefraction ) { waterShader.setUniform( "foamMap", 5 ); } else { waterShader.setUniform( "foamMap", 3 ); } waterShader.setUniform( "waterHeight", waterPlane.getConstant() ); waterShader.setUniform( "amplitude", waterMaxAmplitude ); waterShader.setUniform( "heightFalloffStart", heightFalloffStart ); waterShader.setUniform( "heightFalloffSpeed", heightFalloffSpeed ); } waterShader.apply(); float heightTotal = clipBias + waterMaxAmplitude - waterPlane.getConstant(); Vector3f normal = waterPlane.getNormal(); clipState.setClipPlaneEquation( ClipState.CLIP_PLANE0, normal.x, normal.y, normal.z, heightTotal ); clipState.setEnabled( true ); renderReflection(); clipState.setClipPlaneEquation( ClipState.CLIP_PLANE0, -normal.x, -normal.y, -normal.z, -heightTotal ); if( useRefraction && aboveWater ) { renderRefraction(); } clipState.setEnabled( false ); } else { ts.getTexture().setTranslation( new Vector3f( 0, normalTranslation, 0 ) ); } } public void reloadShader() { GLSLShaderObjectsState testShader = DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState(); try { testShader.load( WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".vert" ), WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".frag" ) ); testShader.apply(); Util.checkGLError(); } catch( OpenGLException e ) { e.printStackTrace(); return; } waterShader.load( WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".vert" ), WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".frag" ) ); LoggingSystem.getLogger().log( Level.INFO, "Shader reloaded..." ); } public void setWaterEffectOnSpatial( Spatial spatial ) { spatial.setRenderState( cullBackFace ); if( isSupported() ) { spatial.setRenderQueueMode( Renderer.QUEUE_SKIP ); spatial.setRenderState( waterShader ); spatial.setRenderState( ts ); } else { spatial.setRenderQueueMode( Renderer.QUEUE_TRANSPARENT ); spatial.setLightCombineMode( LightState.OFF ); spatial.setRenderState( ts ); spatial.setRenderState( as1 ); } spatial.updateRenderState(); } //temporary vectors for mem opt. private Vector3f tmpLocation = new Vector3f(); private Vector3f camReflectPos = new Vector3f(); private Vector3f camReflectDir = new Vector3f(); private Vector3f camReflectUp = new Vector3f(); private Vector3f camReflectLeft = new Vector3f(); private Vector3f camLocation = new Vector3f(); private void renderReflection() { if( aboveWater ) { camLocation.set( cam.getLocation() ); float planeDistance = waterPlane.pseudoDistance( camLocation ); camReflectPos.set( camLocation.subtractLocal( waterPlane.getNormal().mult( planeDistance * 2.0f ) ) ); camLocation.set( cam.getLocation() ).addLocal( cam.getDirection() ); planeDistance = waterPlane.pseudoDistance( camLocation ); camReflectDir.set( camLocation.subtractLocal( waterPlane.getNormal().mult( planeDistance * 2.0f ) ) ).subtractLocal( camReflectPos ).normalizeLocal(); camLocation.set( cam.getLocation() ).addLocal( cam.getUp() ); planeDistance = waterPlane.pseudoDistance( camLocation ); camReflectUp.set( camLocation.subtractLocal( waterPlane.getNormal().mult( planeDistance * 2.0f ) ) ).subtractLocal( camReflectPos ).normalizeLocal(); camReflectLeft.set( camReflectDir ).crossLocal( camReflectUp ).normalizeLocal(); tRenderer.getCamera().getLocation().set( camReflectPos ); tRenderer.getCamera().getDirection().set( camReflectDir ); tRenderer.getCamera().getUp().set( camReflectUp ); tRenderer.getCamera().getLeft().set( camReflectLeft ); } else { tRenderer.getCamera().getLocation().set( cam.getLocation() ); tRenderer.getCamera().getDirection().set( cam.getDirection() ); tRenderer.getCamera().getUp().set( cam.getUp() ); tRenderer.getCamera().getLeft().set( cam.getLeft() ); } tRenderer.updateCamera(); tmpLocation.set( skyBox.getLocalTranslation() ); skyBox.getLocalTranslation().set( tRenderer.getCamera().getLocation() ); skyBox.updateWorldData( 0.0f ); tRenderer.render( renderNode, textureReflect ); skyBox.getLocalTranslation().set( tmpLocation ); skyBox.updateWorldData( 0.0f ); } private void renderRefraction() { tRenderer.getCamera().getLocation().set( cam.getLocation() ); tRenderer.getCamera().getDirection().set( cam.getDirection() ); tRenderer.getCamera().getUp().set( cam.getUp() ); tRenderer.getCamera().getLeft().set( cam.getLeft() ); tRenderer.updateCamera(); int cullMode = skyBox.getCullMode(); skyBox.setCullMode( SceneElement.CULL_ALWAYS ); tRenderer.render( renderNode, textureRefract, textureDepth ); skyBox.setCullMode( cullMode ); } public void setReflectedScene( Node renderNode ) { this.renderNode = renderNode; renderNode.setRenderState( clipState ); renderNode.updateRenderState(); } public void setSkybox( Node skyBox ) { ClipState skyboxClipState = DisplaySystem.getDisplaySystem().getRenderer().createClipState(); skyboxClipState.setEnabled( false ); skyBox.setRenderState( skyboxClipState ); skyBox.updateRenderState(); this.skyBox = skyBox; } private void generateTangentVectors() { waterPlane.getNormal().normalizeLocal(); float ax = waterPlane.getNormal().x * FastMath.rand.nextFloat(); float by = waterPlane.getNormal().y * FastMath.rand.nextFloat(); float cz = waterPlane.getNormal().z * FastMath.rand.nextFloat(); float d = waterPlane.getConstant(); float x = -by - cz - d; float y = -ax - cz - d; float z = -ax - by - d; tangent = new Vector3f( x, y, z ); tangent.normalizeLocal(); binormal = tangent.cross( waterPlane.getNormal() ); } public Camera getCam() { return cam; } public void setCam( Camera cam ) { this.cam = cam; } public ColorRGBA getWaterColorStart() { return waterColorStart; } public void setWaterColorStart( ColorRGBA waterColorStart ) { this.waterColorStart = waterColorStart; } public ColorRGBA getWaterColorEnd() { return waterColorEnd; } public void setWaterColorEnd( ColorRGBA waterColorEnd ) { this.waterColorEnd = waterColorEnd; } public float getHeightFalloffStart() { return heightFalloffStart; } public void setHeightFalloffStart( float heightFalloffStart ) { this.heightFalloffStart = heightFalloffStart; } public float getHeightFalloffSpeed() { return heightFalloffSpeed; } public void setHeightFalloffSpeed( float heightFalloffSpeed ) { this.heightFalloffSpeed = heightFalloffSpeed; } public float getWaterHeight() { return waterPlane.getConstant(); } public void setWaterHeight( float waterHeight ) { this.waterPlane.setConstant( waterHeight ); } public Vector3f getNormal() { return waterPlane.getNormal(); } public void setNormal( Vector3f normal ) { waterPlane.setNormal( normal ); } public float getSpeedReflection() { return speedReflection; } public void setSpeedReflection( float speedReflection ) { this.speedReflection = speedReflection; } public float getSpeedRefraction() { return speedRefraction; } public void setSpeedRefraction( float speedRefraction ) { this.speedRefraction = speedRefraction; } public float getWaterMaxAmplitude() { return waterMaxAmplitude; } public void setWaterMaxAmplitude( float waterMaxAmplitude ) { this.waterMaxAmplitude = waterMaxAmplitude; } public float getClipBias() { return clipBias; } public void setClipBias( float clipBias ) { this.clipBias = clipBias; } public Plane getWaterPlane() { return waterPlane; } public void setWaterPlane( Plane waterPlane ) { this.waterPlane = waterPlane; } public Vector3f getTangent() { return tangent; } public void setTangent( Vector3f tangent ) { this.tangent = tangent; } public Vector3f getBinormal() { return binormal; } public void setBinormal( Vector3f binormal ) { this.binormal = binormal; } public Texture getTextureReflect() { return textureReflect; } public Texture getTextureRefract() { return textureRefract; } public Texture getTextureDepth() { return textureDepth; } }
false
true
public WaterRenderPass( Camera cam, int renderScale, boolean useProjectedShader, boolean useRefraction ) { this.cam = cam; this.useProjectedShader = useProjectedShader; this.useRefraction = useRefraction; if( useRefraction && useProjectedShader && TextureState.getNumberOfFragmentUnits() < 6 || useRefraction && TextureState.getNumberOfFragmentUnits() < 5 ) { useRefraction = false; LoggingSystem.getLogger().log( Level.INFO, "Not enough textureunits, falling back to non refraction water" ); } resetParameters(); DisplaySystem display = DisplaySystem.getDisplaySystem(); waterShader = display.getRenderer().createGLSLShaderObjectsState(); if( !waterShader.isSupported() ) { supported = false; } else { } cullBackFace = display.getRenderer().createCullState(); cullBackFace.setEnabled( true ); cullBackFace.setCullMode( CullState.CS_NONE ); clipState = display.getRenderer().createClipState(); if( isSupported() ) { tRenderer = display.createTextureRenderer( display.getWidth() / renderScale, display.getHeight() / renderScale, false, true, false, false, TextureRenderer.RENDER_TEXTURE_2D, 0 ); if( tRenderer.isSupported() ) { tRenderer.setBackgroundColor( new ColorRGBA( 0.0f, 0.0f, 0.0f, 1.0f ) ); tRenderer.getCamera().setFrustum( cam.getFrustumNear(), cam.getFrustumFar(), cam.getFrustumLeft(), cam.getFrustumRight(), cam.getFrustumTop(), cam.getFrustumBottom() ); tRenderer.forceCopy( true ); textureReflect = new Texture(); textureReflect.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureReflect.setFilter( Texture.FM_LINEAR ); textureReflect.setScale( new Vector3f( -1.0f, 1.0f, 1.0f ) ); textureReflect.setTranslation( new Vector3f( 1.0f, 0.0f, 0.0f ) ); tRenderer.setupTexture( textureReflect ); if( useRefraction ) { textureRefract = new Texture(); textureRefract.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureRefract.setFilter( Texture.FM_LINEAR ); tRenderer.setupTexture( textureRefract ); textureDepth = new Texture(); textureDepth.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureDepth.setFilter( Texture.FM_NEAREST ); textureDepth.setRTTSource( Texture.RTT_SOURCE_DEPTH ); tRenderer.setupTexture( textureDepth ); } ts = display.getRenderer().createTextureState(); ts.setEnabled( true ); Texture t1 = TextureManager.loadTexture( // WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/normalmap3.dds" ), WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/normalmap.png" ), // WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/fisk.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false // Texture.FM_NEAREST ); ts.setTexture( t1, 0 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); ts.setTexture( textureReflect, 1 ); t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/dudvmap.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false ); ts.setTexture( t1, 2 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); if( useRefraction ) { ts.setTexture( textureRefract, 3 ); ts.setTexture( textureDepth, 4 ); } if( useProjectedShader ) { t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/oceanfoam.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR ); if( useRefraction ) { ts.setTexture( t1, 5 ); } else { ts.setTexture( t1, 3 ); } t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); } clipState.setEnabled( true ); clipState.setEnableClipPlane( ClipState.CLIP_PLANE0, true ); if( useProjectedShader ) { if( useRefraction ) { currentShaderStr = projectedShaderRefractionStr; } else { currentShaderStr = projectedShaderStr; } } else { if( useRefraction ) { currentShaderStr = simpleShaderRefractionStr; } else { currentShaderStr = simpleShaderStr; } } waterShader.load( WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".vert" ), WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".frag" ) ); waterShader.setEnabled( true ); } else { supported = false; } } if( !isSupported() ) { ts = display.getRenderer().createTextureState(); ts.setEnabled( true ); Texture t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/water2.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR ); ts.setTexture( t1, 0 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); as1 = display.getRenderer().createAlphaState(); as1.setBlendEnabled( true ); as1.setSrcFunction( AlphaState.SB_SRC_ALPHA ); as1.setDstFunction( AlphaState.DB_ONE_MINUS_SRC_ALPHA ); as1.setEnabled( true ); } }
public WaterRenderPass( Camera cam, int renderScale, boolean useProjectedShader, boolean useRefraction ) { this.cam = cam; this.useProjectedShader = useProjectedShader; this.useRefraction = useRefraction; if( useRefraction && useProjectedShader && TextureState.getNumberOfFragmentUnits() < 6 || useRefraction && TextureState.getNumberOfFragmentUnits() < 5 ) { useRefraction = false; LoggingSystem.getLogger().log( Level.INFO, "Not enough textureunits, falling back to non refraction water" ); } resetParameters(); DisplaySystem display = DisplaySystem.getDisplaySystem(); waterShader = display.getRenderer().createGLSLShaderObjectsState(); if( !waterShader.isSupported() ) { supported = false; } else { } cullBackFace = display.getRenderer().createCullState(); cullBackFace.setEnabled( true ); cullBackFace.setCullMode( CullState.CS_NONE ); clipState = display.getRenderer().createClipState(); if( isSupported() ) { tRenderer = display.createTextureRenderer( display.getWidth() / renderScale, display.getHeight() / renderScale, false, true, false, false, TextureRenderer.RENDER_TEXTURE_2D, 0 ); if( tRenderer.isSupported() ) { tRenderer.setBackgroundColor( new ColorRGBA( 0.0f, 0.0f, 0.0f, 1.0f ) ); tRenderer.getCamera().setFrustum( cam.getFrustumNear(), cam.getFrustumFar(), cam.getFrustumLeft(), cam.getFrustumRight(), cam.getFrustumTop(), cam.getFrustumBottom() ); tRenderer.forceCopy( true ); textureReflect = new Texture(); textureReflect.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureReflect.setFilter( Texture.FM_LINEAR ); textureReflect.setScale( new Vector3f( -1.0f, 1.0f, 1.0f ) ); textureReflect.setTranslation( new Vector3f( 1.0f, 0.0f, 0.0f ) ); tRenderer.setupTexture( textureReflect ); if( useRefraction ) { textureRefract = new Texture(); textureRefract.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureRefract.setFilter( Texture.FM_LINEAR ); tRenderer.setupTexture( textureRefract ); textureDepth = new Texture(); textureDepth.setWrap( Texture.WM_ECLAMP_S_ECLAMP_T ); textureDepth.setFilter( Texture.FM_NEAREST ); textureDepth.setRTTSource( Texture.RTT_SOURCE_DEPTH ); tRenderer.setupTexture( textureDepth ); } ts = display.getRenderer().createTextureState(); ts.setEnabled( true ); Texture t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/normalmap3.dds" ), Texture.MM_LINEAR_LINEAR, // Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false Texture.FM_LINEAR ); ts.setTexture( t1, 0 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); ts.setTexture( textureReflect, 1 ); t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/dudvmap.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1.0f, false ); ts.setTexture( t1, 2 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); if( useRefraction ) { ts.setTexture( textureRefract, 3 ); ts.setTexture( textureDepth, 4 ); } if( useProjectedShader ) { t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/oceanfoam.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR ); if( useRefraction ) { ts.setTexture( t1, 5 ); } else { ts.setTexture( t1, 3 ); } t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); } clipState.setEnabled( true ); clipState.setEnableClipPlane( ClipState.CLIP_PLANE0, true ); if( useProjectedShader ) { if( useRefraction ) { currentShaderStr = projectedShaderRefractionStr; } else { currentShaderStr = projectedShaderStr; } } else { if( useRefraction ) { currentShaderStr = simpleShaderRefractionStr; } else { currentShaderStr = simpleShaderStr; } } waterShader.load( WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".vert" ), WaterRenderPass.class.getClassLoader().getResource( currentShaderStr + ".frag" ) ); waterShader.setEnabled( true ); } else { supported = false; } } if( !isSupported() ) { ts = display.getRenderer().createTextureState(); ts.setEnabled( true ); Texture t1 = TextureManager.loadTexture( WaterRenderPass.class.getClassLoader().getResource( "com/jmex/effects/water/data/water2.png" ), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR ); ts.setTexture( t1, 0 ); t1.setWrap( Texture.WM_WRAP_S_WRAP_T ); as1 = display.getRenderer().createAlphaState(); as1.setBlendEnabled( true ); as1.setSrcFunction( AlphaState.SB_SRC_ALPHA ); as1.setDstFunction( AlphaState.DB_ONE_MINUS_SRC_ALPHA ); as1.setEnabled( true ); } }
diff --git a/src/ca/teamTen/recitopia/test/LocalCacheTest.java b/src/ca/teamTen/recitopia/test/LocalCacheTest.java index abd34f5..9615bf3 100644 --- a/src/ca/teamTen/recitopia/test/LocalCacheTest.java +++ b/src/ca/teamTen/recitopia/test/LocalCacheTest.java @@ -1,50 +1,50 @@ package ca.teamTen.recitopia.test; import java.util.ArrayList; import java.util.Arrays; import ca.teamTen.recitopia.LocalCache; import ca.teamTen.recitopia.Recipe; import ca.teamTen.recitopia.RecipeBook; /** * jUnit tests for LocalCache RecipeBook. * * Test conformance to RecipeBook interface as well as */ public class LocalCacheTest extends RecipeBookTest { @Override protected RecipeBook createRecipeBook() { return new LocalCache(defaultRecipes.size()); } public void testSizeLimit() { addTestData(); int recipeCount = defaultRecipes.size(); Recipe newRecipe = new Recipe("A completely new recipe", new ArrayList<String>(Arrays.asList("spiky melon", "salt", "cooking oil")), "chop, fry, eat", "[email protected]"); recipeBook.addRecipe(newRecipe); - for (int i = 0; i < defaultRecipes.size(); i++) { + for (int i = 1; i <= defaultRecipes.size(); i++) { Recipe recipe = defaultRecipes.get(recipeCount - i); if (i >= recipeCount) { assertEquals(recipeBook.query(recipe.showAuthor()).length, 0); // these recipes should not be present } else { assertEquals(recipeBook.query(recipe.showAuthor()).length, 1); // these recipes should be present } } assertEquals(recipeBook.query(newRecipe.showAuthor()).length, 1); // the new recipe should be present } }
true
true
public void testSizeLimit() { addTestData(); int recipeCount = defaultRecipes.size(); Recipe newRecipe = new Recipe("A completely new recipe", new ArrayList<String>(Arrays.asList("spiky melon", "salt", "cooking oil")), "chop, fry, eat", "[email protected]"); recipeBook.addRecipe(newRecipe); for (int i = 0; i < defaultRecipes.size(); i++) { Recipe recipe = defaultRecipes.get(recipeCount - i); if (i >= recipeCount) { assertEquals(recipeBook.query(recipe.showAuthor()).length, 0); // these recipes should not be present } else { assertEquals(recipeBook.query(recipe.showAuthor()).length, 1); // these recipes should be present } } assertEquals(recipeBook.query(newRecipe.showAuthor()).length, 1); // the new recipe should be present }
public void testSizeLimit() { addTestData(); int recipeCount = defaultRecipes.size(); Recipe newRecipe = new Recipe("A completely new recipe", new ArrayList<String>(Arrays.asList("spiky melon", "salt", "cooking oil")), "chop, fry, eat", "[email protected]"); recipeBook.addRecipe(newRecipe); for (int i = 1; i <= defaultRecipes.size(); i++) { Recipe recipe = defaultRecipes.get(recipeCount - i); if (i >= recipeCount) { assertEquals(recipeBook.query(recipe.showAuthor()).length, 0); // these recipes should not be present } else { assertEquals(recipeBook.query(recipe.showAuthor()).length, 1); // these recipes should be present } } assertEquals(recipeBook.query(newRecipe.showAuthor()).length, 1); // the new recipe should be present }
diff --git a/src/java/davmail/exchange/ews/EWSMethod.java b/src/java/davmail/exchange/ews/EWSMethod.java index a01dad2..793f7b0 100644 --- a/src/java/davmail/exchange/ews/EWSMethod.java +++ b/src/java/davmail/exchange/ews/EWSMethod.java @@ -1,1074 +1,1070 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2010 Mickael Guessant * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail.exchange.ews; import davmail.BundleMessage; import davmail.exchange.XMLStreamUtil; import davmail.http.DavGatewayHttpClientFacade; import davmail.ui.tray.DavGatewayTray; import davmail.util.StringUtil; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.log4j.Logger; import org.codehaus.stax2.typed.TypedXMLStreamReader; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.*; import java.util.*; import java.util.zip.GZIPInputStream; /** * EWS SOAP method. */ public abstract class EWSMethod extends PostMethod { protected static final Logger LOGGER = Logger.getLogger(EWSMethod.class); protected FolderQueryTraversal traversal; protected BaseShape baseShape; protected boolean includeMimeContent; protected FolderId folderId; protected FolderId savedItemFolderId; protected FolderId toFolderId; protected FolderId parentFolderId; protected ItemId itemId; protected ItemId parentItemId; protected Set<FieldURI> additionalProperties; protected Disposal deleteType; protected Set<AttributeOption> methodOptions; protected ElementOption unresolvedEntry; // paging request protected int maxCount; protected int offset; // paging response protected boolean includesLastItemInRange; protected List<FieldUpdate> updates; protected FileAttachment attachment; protected String attachmentId; protected final String itemType; protected final String methodName; protected final String responseCollectionName; protected List<Item> responseItems; protected String errorDetail; protected Item item; protected SearchExpression searchExpression; protected String serverVersion; /** * Build EWS method * * @param itemType item type * @param methodName method name */ public EWSMethod(String itemType, String methodName) { this(itemType, methodName, itemType + 's'); } /** * Build EWS method * * @param itemType item type * @param methodName method name * @param responseCollectionName item response collection name */ public EWSMethod(String itemType, String methodName, String responseCollectionName) { super("/ews/exchange.asmx"); this.itemType = itemType; this.methodName = methodName; this.responseCollectionName = responseCollectionName; setRequestHeader("Accept-Encoding", "gzip"); setRequestEntity(new RequestEntity() { byte[] content; public boolean isRepeatable() { return true; } public void writeRequest(OutputStream outputStream) throws IOException { if (content == null) { content = generateSoapEnvelope(); } outputStream.write(content); } public long getContentLength() { if (content == null) { content = generateSoapEnvelope(); } return content.length; } public String getContentType() { return "text/xml; charset=UTF-8"; } }); } @Override public String getName() { return "POST"; } protected void addAdditionalProperty(FieldURI additionalProperty) { if (additionalProperties == null) { additionalProperties = new HashSet<FieldURI>(); } additionalProperties.add(additionalProperty); } protected void addMethodOption(AttributeOption attributeOption) { if (methodOptions == null) { methodOptions = new HashSet<AttributeOption>(); } methodOptions.add(attributeOption); } protected void setSearchExpression(SearchExpression searchExpression) { this.searchExpression = searchExpression; } protected void writeShape(Writer writer) throws IOException { if (baseShape != null) { writer.write("<m:"); writer.write(itemType); writer.write("Shape>"); baseShape.write(writer); if (includeMimeContent) { writer.write("<t:IncludeMimeContent>true</t:IncludeMimeContent>"); } if (additionalProperties != null) { writer.write("<t:AdditionalProperties>"); StringBuilder buffer = new StringBuilder(); for (FieldURI fieldURI : additionalProperties) { fieldURI.appendTo(buffer); } writer.write(buffer.toString()); writer.write("</t:AdditionalProperties>"); } writer.write("</m:"); writer.write(itemType); writer.write("Shape>"); } } protected void writeItemId(Writer writer) throws IOException { if (itemId != null) { if (updates == null) { writer.write("<m:ItemIds>"); } itemId.write(writer); if (updates == null) { writer.write("</m:ItemIds>"); } } } protected void writeParentItemId(Writer writer) throws IOException { if (parentItemId != null) { writer.write("<m:ParentItemId Id=\""); writer.write(parentItemId.id); if (parentItemId.changeKey != null) { writer.write("\" ChangeKey=\""); writer.write(parentItemId.changeKey); } writer.write("\"/>"); } } protected void writeFolderId(Writer writer) throws IOException { if (folderId != null) { if (updates == null) { writer.write("<m:FolderIds>"); } folderId.write(writer); if (updates == null) { writer.write("</m:FolderIds>"); } } } protected void writeSavedItemFolderId(Writer writer) throws IOException { if (savedItemFolderId != null) { writer.write("<m:SavedItemFolderId>"); savedItemFolderId.write(writer); writer.write("</m:SavedItemFolderId>"); } } protected void writeToFolderId(Writer writer) throws IOException { if (toFolderId != null) { writer.write("<m:ToFolderId>"); toFolderId.write(writer); writer.write("</m:ToFolderId>"); } } protected void writeParentFolderId(Writer writer) throws IOException { if (parentFolderId != null) { writer.write("<m:ParentFolderId"); if (item == null) { writer.write("s"); } writer.write(">"); parentFolderId.write(writer); writer.write("</m:ParentFolderId"); if (item == null) { writer.write("s"); } writer.write(">"); } } protected void writeItem(Writer writer) throws IOException { if (item != null) { writer.write("<m:"); writer.write(itemType); writer.write("s>"); item.write(writer); writer.write("</m:"); writer.write(itemType); writer.write("s>"); } } protected void writeRestriction(Writer writer) throws IOException { if (searchExpression != null) { writer.write("<m:Restriction>"); StringBuilder buffer = new StringBuilder(); searchExpression.appendTo(buffer); writer.write(buffer.toString()); writer.write("</m:Restriction>"); } } protected void startChanges(Writer writer) throws IOException { //noinspection VariableNotUsedInsideIf if (updates != null) { writer.write("<m:"); writer.write(itemType); writer.write("Changes>"); writer.write("<t:"); writer.write(itemType); writer.write("Change>"); } } protected void writeUpdates(Writer writer) throws IOException { if (updates != null) { writer.write("<t:Updates>"); for (FieldUpdate fieldUpdate : updates) { fieldUpdate.write(itemType, writer); } writer.write("</t:Updates>"); } } protected void writeUnresolvedEntry(Writer writer) throws IOException { if (unresolvedEntry != null) { unresolvedEntry.write(writer); } } protected void endChanges(Writer writer) throws IOException { //noinspection VariableNotUsedInsideIf if (updates != null) { writer.write("</t:"); writer.write(itemType); writer.write("Change>"); writer.write("</m:"); writer.write(itemType); writer.write("Changes>"); } } protected byte[] generateSoapEnvelope() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8"); writer.write("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" " + "xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\">" + ""); if (serverVersion != null) { writer.write("<soap:Header><t:RequestServerVersion Version=\""); writer.write(serverVersion); writer.write("\"/></soap:Header>"); } writer.write("<soap:Body>"); writer.write("<m:"); writer.write(methodName); if (traversal != null) { traversal.write(writer); } if (deleteType != null) { deleteType.write(writer); } if (methodOptions != null) { for (AttributeOption attributeOption : methodOptions) { attributeOption.write(writer); } } writer.write(">"); writeSoapBody(writer); writer.write("</m:"); writer.write(methodName); writer.write(">"); writer.write("</soap:Body>" + "</soap:Envelope>"); writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); } protected void writeSoapBody(Writer writer) throws IOException { startChanges(writer); writeShape(writer); writeIndexedPageItemView(writer); writeRestriction(writer); writeParentFolderId(writer); writeToFolderId(writer); writeItemId(writer); writeParentItemId(writer); writeAttachments(writer); writeAttachmentId(writer); writeFolderId(writer); writeSavedItemFolderId(writer); writeItem(writer); writeUpdates(writer); writeUnresolvedEntry(writer); endChanges(writer); } protected void writeIndexedPageItemView(Writer writer) throws IOException { if (maxCount > 0) { writer.write("<m:IndexedPageItemView MaxEntriesReturned=\""); writer.write(String.valueOf(maxCount)); writer.write("\" Offset=\""); writer.write(String.valueOf(offset)); writer.write("\" BasePoint=\"Beginning\"/>"); } } protected void writeAttachmentId(Writer writer) throws IOException { if (attachmentId != null) { if ("CreateAttachment".equals(methodName)) { writer.write("<m:AttachmentShape>"); writer.write("<t:IncludeMimeContent>true</t:IncludeMimeContent>"); writer.write("</m:AttachmentShape>"); } writer.write("<m:AttachmentIds>"); writer.write("<t:AttachmentId Id=\""); writer.write(attachmentId); writer.write("\"/>"); writer.write("</m:AttachmentIds>"); } } protected void writeAttachments(Writer writer) throws IOException { if (attachment != null) { writer.write("<m:Attachments>"); attachment.write(writer); writer.write("</m:Attachments>"); } } /** * Get Exchange server version, Exchange2010 or Exchange2007_SP1 * * @return server version */ public String getServerVersion() { return serverVersion; } /** * Set Exchange server version, Exchange2010 or Exchange2007_SP1 * * @param serverVersion server version */ public void setServerVersion(String serverVersion) { this.serverVersion = serverVersion; } /** * Meeting attendee object */ public static class Attendee { /** * attendee role */ public String role; /** * attendee email address */ public String email; /** * attendee participation status */ public String partstat; /** * attendee fullname */ public String name; } /** * Recurring event occurrence */ public static class Occurrence { /** * Original occurence start date */ public String originalStart; } /** * Item */ public static class Item extends HashMap<String, String> { /** * Item type. */ public String type; protected byte[] mimeContent; protected List<FieldUpdate> fieldUpdates; protected List<FileAttachment> attachments; protected List<Attendee> attendees; protected final List<String> fieldNames = new ArrayList<String>(); protected List<Occurrence> occurrences; @Override public String toString() { return "type: " + type + ' ' + super.toString(); } @Override public String put(String key, String value) { if (value != null) { if (get(key) == null) { fieldNames.add(key); } return super.put(key, value); } else { return null; } } /** * Write XML content to writer. * * @param writer writer * @throws IOException on error */ public void write(Writer writer) throws IOException { writer.write("<t:"); writer.write(type); writer.write(">"); // write ordered fields for (String key : fieldNames) { if ("MeetingTimeZone".equals(key)) { writer.write("<t:MeetingTimeZone TimeZoneName=\""); writer.write(StringUtil.xmlEncodeAttribute(get(key))); writer.write("\"></t:MeetingTimeZone>"); } else if ("StartTimeZone".equals(key)) { writer.write("<t:StartTimeZone Id=\""); writer.write(StringUtil.xmlEncodeAttribute(get(key))); writer.write("\"></t:StartTimeZone>"); } else { writer.write("<t:"); writer.write(key); writer.write(">"); writer.write(StringUtil.xmlEncode(get(key))); writer.write("</t:"); writer.write(key); writer.write(">"); } } if (mimeContent != null) { writer.write("<t:MimeContent>"); writer.write(new String(mimeContent)); writer.write("</t:MimeContent>"); } if (fieldUpdates != null) { for (FieldUpdate fieldUpdate : fieldUpdates) { fieldUpdate.write(null, writer); } } writer.write("</t:"); writer.write(type); writer.write(">"); } /** * Field updates. * * @param fieldUpdates field updates */ public void setFieldUpdates(List<FieldUpdate> fieldUpdates) { this.fieldUpdates = fieldUpdates; } /** * Get property value as int * * @param key property response name * @return property value */ public int getInt(String key) { int result = 0; String value = get(key); if (value != null && value.length() > 0) { result = Integer.parseInt(value); } return result; } /** * Get property value as long * * @param key property response name * @return property value */ public long getLong(String key) { long result = 0; String value = get(key); if (value != null && value.length() > 0) { result = Long.parseLong(value); } return result; } /** * Get property value as boolean * * @param key property response name * @return property value */ public boolean getBoolean(String key) { boolean result = false; String value = get(key); if (value != null && value.length() > 0) { result = Boolean.parseBoolean(value); } return result; } /** * Get file attachment by file name * * @param attachmentName attachment name * @return attachment */ public FileAttachment getAttachmentByName(String attachmentName) { FileAttachment result = null; if (attachments != null) { for (FileAttachment attachment : attachments) { if (attachmentName.equals(attachment.name)) { result = attachment; break; } } } return result; } /** * Get all attendees. * * @return all attendees */ public List<Attendee> getAttendees() { return attendees; } /** * Add attendee. * * @param attendee attendee object */ public void addAttendee(Attendee attendee) { if (attendees == null) { attendees = new ArrayList<Attendee>(); } attendees.add(attendee); } /** * Add occurrence. * * @param occurrence event occurence */ public void addOccurrence(Occurrence occurrence) { if (occurrences == null) { occurrences = new ArrayList<Occurrence>(); } occurrences.add(occurrence); } /** * Get occurences. * * @return event occurences */ public List<Occurrence> getOccurrences() { return occurrences; } } /** * Check method success. * * @throws EWSException on error */ public void checkSuccess() throws EWSException { if (errorDetail != null) { if (!"ErrorAccessDenied".equals(errorDetail) && !"ErrorMailRecipientNotFound".equals(errorDetail) && !"ErrorItemNotFound".equals(errorDetail) ) { try { throw new EWSException(errorDetail + "\n request: " + new String(generateSoapEnvelope(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new EWSException(e.getMessage()); } } } } @Override public int getStatusCode() { if ("ErrorAccessDenied".equals(errorDetail)) { return HttpStatus.SC_FORBIDDEN; } else { return super.getStatusCode(); } } /** * Get response items. * * @return response items * @throws EWSException on error */ public List<Item> getResponseItems() throws EWSException { checkSuccess(); if (responseItems != null) { return responseItems; } else { return new ArrayList<Item>(); } } /** * Get single response item. * * @return response item * @throws EWSException on error */ public Item getResponseItem() throws EWSException { checkSuccess(); if (responseItems != null && responseItems.size() == 1) { return responseItems.get(0); } else { return null; } } /** * Get response mime content. * * @return mime content * @throws EWSException on error */ public byte[] getMimeContent() throws EWSException { checkSuccess(); Item responseItem = getResponseItem(); if (responseItem != null) { return responseItem.mimeContent; } else { return null; } } protected String handleTag(XMLStreamReader reader, String localName) throws XMLStreamException { String result = null; int event = reader.getEventType(); if (event == XMLStreamConstants.START_ELEMENT && localName.equals(reader.getLocalName())) { while (reader.hasNext() && !((event == XMLStreamConstants.END_ELEMENT && localName.equals(reader.getLocalName())))) { event = reader.next(); if (event == XMLStreamConstants.CHARACTERS) { result = reader.getText(); } } } return result; } protected void handleErrors(XMLStreamReader reader) throws XMLStreamException { String result = handleTag(reader, "ResponseCode"); if (errorDetail == null && result != null && !"NoError".equals(result) && !"ErrorNameResolutionMultipleResults".equals(result) && !"ErrorNameResolutionNoResults".equals(result) && !"ErrorFolderExists".equals(result) ) { errorDetail = result; } if (XMLStreamUtil.isStartTag(reader, "faultstring")) { errorDetail = XMLStreamUtil.getElementText(reader); } } protected Item handleItem(XMLStreamReader reader) throws XMLStreamException { Item responseItem = new Item(); responseItem.type = reader.getLocalName(); while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, responseItem.type)) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); String value = null; if ("ExtendedProperty".equals(tagLocalName)) { addExtendedPropertyValue(reader, responseItem); } else if (tagLocalName.endsWith("MimeContent")) { handleMimeContent(reader, responseItem); } else if ("Attachments".equals(tagLocalName)) { responseItem.attachments = handleAttachments(reader); } else if ("EmailAddresses".equals(tagLocalName)) { handleEmailAddresses(reader, responseItem); } else if ("RequiredAttendees".equals(tagLocalName) || "OptionalAttendees".equals(tagLocalName)) { handleAttendees(reader, responseItem, tagLocalName); } else if ("ModifiedOccurrences".equals(tagLocalName)) { handleModifiedOccurrences(reader, responseItem); } else { if (tagLocalName.endsWith("Id")) { value = getAttributeValue(reader, "Id"); // get change key responseItem.put("ChangeKey", getAttributeValue(reader, "ChangeKey")); } if (value == null) { value = getTagContent(reader); } if (value != null) { responseItem.put(tagLocalName, value); } } } } return responseItem; } protected void handleEmailAddresses(XMLStreamReader reader, Item item) throws XMLStreamException { while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "EmailAddresses"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("Entry".equals(tagLocalName)) { item.put(reader.getAttributeValue(null, "Key"), XMLStreamUtil.getElementText(reader)); } } } } protected void handleAttendees(XMLStreamReader reader, Item item, String attendeeType) throws XMLStreamException { while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, attendeeType))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("Attendee".equals(tagLocalName)) { handleAttendee(reader, item, attendeeType); } } } } protected void handleModifiedOccurrences(XMLStreamReader reader, Item item) throws XMLStreamException { while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "ModifiedOccurrences"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("Occurrence".equals(tagLocalName)) { handleOccurrence(reader, item); } } } } protected void handleOccurrence(XMLStreamReader reader, Item item) throws XMLStreamException { while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "Occurrence"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("OriginalStart".equals(tagLocalName)) { Occurrence occurrence = new Occurrence(); occurrence.originalStart = XMLStreamUtil.getElementText(reader); item.addOccurrence(occurrence); } } } } protected void handleAttendee(XMLStreamReader reader, Item item, String attendeeType) throws XMLStreamException { Attendee attendee = new Attendee(); if ("RequiredAttendees".equals(attendeeType)) { attendee.role = "REQ-PARTICIPANT"; } else { attendee.role = "OPT-PARTICIPANT"; } while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "Attendee"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("EmailAddress".equals(tagLocalName)) { attendee.email = reader.getElementText(); } else if ("Name".equals(tagLocalName)) { attendee.name = XMLStreamUtil.getElementText(reader); } else if ("ResponseType".equals(tagLocalName)) { String responseType = XMLStreamUtil.getElementText(reader); if ("Accept".equals(responseType)) { attendee.partstat = "ACCEPTED"; } else if ("Tentative".equals(responseType)) { attendee.partstat = "TENTATIVE"; } else if ("Decline".equals(responseType)) { attendee.partstat = "DECLINED"; } else { attendee.partstat = "NEEDS-ACTION"; } } } } item.addAttendee(attendee); } protected List<FileAttachment> handleAttachments(XMLStreamReader reader) throws XMLStreamException { List<FileAttachment> attachments = new ArrayList<FileAttachment>(); while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "Attachments"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("FileAttachment".equals(tagLocalName)) { attachments.add(handleFileAttachment(reader)); } } } return attachments; } protected FileAttachment handleFileAttachment(XMLStreamReader reader) throws XMLStreamException { FileAttachment fileAttachment = new FileAttachment(); while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "FileAttachment"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("AttachmentId".equals(tagLocalName)) { fileAttachment.attachmentId = getAttributeValue(reader, "Id"); } else if ("Name".equals(tagLocalName)) { fileAttachment.name = getTagContent(reader); } else if ("ContentType".equals(tagLocalName)) { fileAttachment.contentType = getTagContent(reader); } } } return fileAttachment; } protected void handleMimeContent(XMLStreamReader reader, Item responseItem) throws XMLStreamException { if (reader instanceof TypedXMLStreamReader) { // Stax2 parser: use enhanced base64 conversion responseItem.mimeContent = ((TypedXMLStreamReader) reader).getElementAsBinary(); } else { // failover: slow and memory consuming conversion byte[] base64MimeContent = reader.getElementText().getBytes(); responseItem.mimeContent = Base64.decodeBase64(base64MimeContent); } } protected void addExtendedPropertyValue(XMLStreamReader reader, Item item) throws XMLStreamException { String propertyTag = null; String propertyValue = null; while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "ExtendedProperty"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { String tagLocalName = reader.getLocalName(); if ("ExtendedFieldURI".equals(tagLocalName)) { propertyTag = getAttributeValue(reader, "PropertyTag"); // property name is in PropertyId or PropertyName with DistinguishedPropertySetId if (propertyTag == null) { propertyTag = getAttributeValue(reader, "PropertyId"); } if (propertyTag == null) { propertyTag = getAttributeValue(reader, "PropertyName"); } } else if ("Value".equals(tagLocalName)) { propertyValue = XMLStreamUtil.getElementText(reader); } else if ("Values".equals(tagLocalName)) { StringBuilder buffer = new StringBuilder(); while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "Values"))) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { if (buffer.length() > 0) { buffer.append(','); } String singleValue = XMLStreamUtil.getElementText(reader); if (singleValue != null) { buffer.append(singleValue); } } } propertyValue = buffer.toString(); } } } if ((propertyTag != null) && (propertyValue != null)) { item.put(propertyTag, propertyValue); } } protected String getTagContent(XMLStreamReader reader) throws XMLStreamException { String tagLocalName = reader.getLocalName(); while (reader.hasNext() && !(reader.getEventType() == XMLStreamConstants.END_ELEMENT)) { reader.next(); if (reader.getEventType() == XMLStreamConstants.CHARACTERS) { return reader.getText(); } } // empty tag if (reader.hasNext()) { return null; } else { throw new XMLStreamException("End element for " + tagLocalName + " not found"); } } protected String getAttributeValue(XMLStreamReader reader, String attributeName) { for (int i = 0; i < reader.getAttributeCount(); i++) { if (attributeName.equals(reader.getAttributeLocalName(i))) { return reader.getAttributeValue(i); } } return null; } @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { Header contentTypeHeader = getResponseHeader("Content-Type"); if (contentTypeHeader != null && "text/xml; charset=utf-8".equals(contentTypeHeader.getValue())) { try { if (DavGatewayHttpClientFacade.isGzipEncoded(this)) { processResponseStream(new GZIPInputStream(getResponseBodyAsStream())); } else { processResponseStream(getResponseBodyAsStream()); } } catch (IOException e) { LOGGER.error("Error while parsing soap response: " + e, e); } } } protected void processResponseStream(InputStream inputStream) { responseItems = new ArrayList<Item>(); XMLStreamReader reader; try { inputStream = new FilterInputStream(inputStream) { int totalCount; int lastLogCount; @Override public int read(byte[] buffer, int offset, int length) throws IOException { int count = super.read(buffer, offset, length); - // workaround for Exchange bug: replace xml 1.0 header with xml 1.1 - if (totalCount == 0 && count > 18 && buffer[17] == '0') { - buffer[17] = '1'; - } totalCount += count; if (totalCount - lastLogCount > 1024 * 128) { DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS", String.valueOf(totalCount / 1024), EWSMethod.this.getURI())); DavGatewayTray.switchIcon(); lastLogCount = totalCount; } return count; } }; reader = XMLStreamUtil.createXMLStreamReader(inputStream); while (reader.hasNext()) { reader.next(); handleErrors(reader); if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) { String majorVersion = getAttributeValue(reader, "MajorVersion"); if ("14".equals(majorVersion)) { serverVersion = "Exchange2010"; } else { serverVersion = "Exchange2007_SP1"; } } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) { includesLastItemInRange = "true".equals(reader.getAttributeValue(null, "IncludesLastItemInRange")); } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) { handleItems(reader); } else { handleCustom(reader); } } } catch (XMLStreamException e) { LOGGER.error("Error while parsing soap response: " + e, e); } if (errorDetail != null) { LOGGER.debug(errorDetail); } } @SuppressWarnings({"NoopMethodInAbstractClass"}) protected void handleCustom(XMLStreamReader reader) throws XMLStreamException { // override to handle custom content } private void handleItems(XMLStreamReader reader) throws XMLStreamException { while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, responseCollectionName)) { reader.next(); if (XMLStreamUtil.isStartTag(reader)) { responseItems.add(handleItem(reader)); } } } }
true
true
protected void processResponseStream(InputStream inputStream) { responseItems = new ArrayList<Item>(); XMLStreamReader reader; try { inputStream = new FilterInputStream(inputStream) { int totalCount; int lastLogCount; @Override public int read(byte[] buffer, int offset, int length) throws IOException { int count = super.read(buffer, offset, length); // workaround for Exchange bug: replace xml 1.0 header with xml 1.1 if (totalCount == 0 && count > 18 && buffer[17] == '0') { buffer[17] = '1'; } totalCount += count; if (totalCount - lastLogCount > 1024 * 128) { DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS", String.valueOf(totalCount / 1024), EWSMethod.this.getURI())); DavGatewayTray.switchIcon(); lastLogCount = totalCount; } return count; } }; reader = XMLStreamUtil.createXMLStreamReader(inputStream); while (reader.hasNext()) { reader.next(); handleErrors(reader); if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) { String majorVersion = getAttributeValue(reader, "MajorVersion"); if ("14".equals(majorVersion)) { serverVersion = "Exchange2010"; } else { serverVersion = "Exchange2007_SP1"; } } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) { includesLastItemInRange = "true".equals(reader.getAttributeValue(null, "IncludesLastItemInRange")); } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) { handleItems(reader); } else { handleCustom(reader); } } } catch (XMLStreamException e) { LOGGER.error("Error while parsing soap response: " + e, e); } if (errorDetail != null) { LOGGER.debug(errorDetail); } }
protected void processResponseStream(InputStream inputStream) { responseItems = new ArrayList<Item>(); XMLStreamReader reader; try { inputStream = new FilterInputStream(inputStream) { int totalCount; int lastLogCount; @Override public int read(byte[] buffer, int offset, int length) throws IOException { int count = super.read(buffer, offset, length); totalCount += count; if (totalCount - lastLogCount > 1024 * 128) { DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS", String.valueOf(totalCount / 1024), EWSMethod.this.getURI())); DavGatewayTray.switchIcon(); lastLogCount = totalCount; } return count; } }; reader = XMLStreamUtil.createXMLStreamReader(inputStream); while (reader.hasNext()) { reader.next(); handleErrors(reader); if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) { String majorVersion = getAttributeValue(reader, "MajorVersion"); if ("14".equals(majorVersion)) { serverVersion = "Exchange2010"; } else { serverVersion = "Exchange2007_SP1"; } } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) { includesLastItemInRange = "true".equals(reader.getAttributeValue(null, "IncludesLastItemInRange")); } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) { handleItems(reader); } else { handleCustom(reader); } } } catch (XMLStreamException e) { LOGGER.error("Error while parsing soap response: " + e, e); } if (errorDetail != null) { LOGGER.debug(errorDetail); } }
diff --git a/src/main/java/burst/reader/web/ExtendedRedirectResult.java b/src/main/java/burst/reader/web/ExtendedRedirectResult.java index 1f7a1a3..65615b1 100644 --- a/src/main/java/burst/reader/web/ExtendedRedirectResult.java +++ b/src/main/java/burst/reader/web/ExtendedRedirectResult.java @@ -1,53 +1,54 @@ package burst.reader.web; import com.opensymphony.xwork2.ActionInvocation; import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.StrutsResultSupport; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import static javax.servlet.http.HttpServletResponse.SC_FOUND; /** * Created with IntelliJ IDEA. * User: Burst * Date: 13-4-4 * Time: 下午9:43 * To change this template use File | Settings | File Templates. */ public class ExtendedRedirectResult extends StrutsResultSupport { private int statusCode = SC_FOUND; public void setStatusCode(int statusCode) { this.statusCode = statusCode; } @Override protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); if(request.getHeader("User-Agent").toLowerCase().indexOf("untrusted/1.0") != -1) { - response.sendRedirect(finalLocation); + response.setContentType("text/vnd.wap.wml"); PrintWriter writer = response.getWriter(); - writer.print("<html><head>"); - writer.print("<meta http-equiv=\"refresh\" content=\"0; url=" + finalLocation + "\">"); - writer.print("</head></html>"); + writer.print("<?xml version=\"1.0\"?><!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">"); + writer.print("<wml><head>"); + writer.print("<meta http-equiv=\"Content-Type\" content=\"text/vnd.wap.wml;charset=UTF-8\"/>"); + writer.print("</head><card id=\"main\" title=\"redirecting...\" onenterforward=\"" + finalLocation + "\"><p>redirecting...</p></card></wml>"); writer.close(); } else { if (SC_FOUND == statusCode) { response.sendRedirect(finalLocation); } else { response.setStatus(statusCode); response.setHeader("Location", finalLocation); response.getWriter().write(finalLocation); response.getWriter().close(); } } } }
false
true
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); if(request.getHeader("User-Agent").toLowerCase().indexOf("untrusted/1.0") != -1) { response.sendRedirect(finalLocation); PrintWriter writer = response.getWriter(); writer.print("<html><head>"); writer.print("<meta http-equiv=\"refresh\" content=\"0; url=" + finalLocation + "\">"); writer.print("</head></html>"); writer.close(); } else { if (SC_FOUND == statusCode) { response.sendRedirect(finalLocation); } else { response.setStatus(statusCode); response.setHeader("Location", finalLocation); response.getWriter().write(finalLocation); response.getWriter().close(); } } }
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); if(request.getHeader("User-Agent").toLowerCase().indexOf("untrusted/1.0") != -1) { response.setContentType("text/vnd.wap.wml"); PrintWriter writer = response.getWriter(); writer.print("<?xml version=\"1.0\"?><!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">"); writer.print("<wml><head>"); writer.print("<meta http-equiv=\"Content-Type\" content=\"text/vnd.wap.wml;charset=UTF-8\"/>"); writer.print("</head><card id=\"main\" title=\"redirecting...\" onenterforward=\"" + finalLocation + "\"><p>redirecting...</p></card></wml>"); writer.close(); } else { if (SC_FOUND == statusCode) { response.sendRedirect(finalLocation); } else { response.setStatus(statusCode); response.setHeader("Location", finalLocation); response.getWriter().write(finalLocation); response.getWriter().close(); } } }
diff --git a/src/main/java/com/almuramc/aqualock/bukkit/display/button/ApplyButton.java b/src/main/java/com/almuramc/aqualock/bukkit/display/button/ApplyButton.java index 7f4ed11..e7137a1 100644 --- a/src/main/java/com/almuramc/aqualock/bukkit/display/button/ApplyButton.java +++ b/src/main/java/com/almuramc/aqualock/bukkit/display/button/ApplyButton.java @@ -1,137 +1,145 @@ /* * This file is part of Aqualock. * * Copyright (c) 2012, AlmuraDev <http://www.almuramc.com/> * Aqualock is licensed under the Almura Development License. * * Aqualock 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. * * Aqualock 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. If not, * see <http://www.gnu.org/licenses/> for the GNU General Public License. */ package com.almuramc.aqualock.bukkit.display.button; import java.util.ArrayList; import java.util.List; import com.almuramc.aqualock.bukkit.AqualockPlugin; import com.almuramc.aqualock.bukkit.display.AquaPanel; import com.almuramc.aqualock.bukkit.display.checkbox.EveryoneCheckbox; import com.almuramc.aqualock.bukkit.display.field.CloseTimerField; import com.almuramc.aqualock.bukkit.display.field.CoOwnerField; import com.almuramc.aqualock.bukkit.display.field.DamageField; import com.almuramc.aqualock.bukkit.display.field.OwnerField; import com.almuramc.aqualock.bukkit.display.field.PasswordField; import com.almuramc.aqualock.bukkit.display.field.UseCostField; import com.almuramc.aqualock.bukkit.display.field.UserField; import com.almuramc.aqualock.bukkit.util.LockUtil; import org.getspout.spoutapi.event.screen.ButtonClickEvent; import org.getspout.spoutapi.gui.GenericButton; import org.getspout.spoutapi.gui.Widget; import org.bukkit.Location; public class ApplyButton extends GenericButton { private final AqualockPlugin plugin; public ApplyButton(AqualockPlugin plugin) { super("Apply"); this.plugin = plugin; } @Override public void onButtonClick(ButtonClickEvent event) { final AquaPanel panel = (AquaPanel) event.getScreen(); String owner = ""; List<String> coowners = null; List<String> users = null; String password = ""; double cost = 0; int damage = 0; long timer = 0; for (Widget widget : panel.getAttachedWidgets()) { final Class clazz = widget.getClass(); if (clazz.equals(OwnerField.class)) { owner = ((OwnerField) widget).getText(); } else if (clazz.equals(PasswordField.class)) { password = ((PasswordField) widget).getText(); } else if (clazz.equals(CoOwnerField.class)) { coowners = parseFieldToList(((CoOwnerField) widget).getText()); } else if (clazz.equals(UserField.class)) { boolean everyone = false; for (Widget inner : panel.getAttachedWidgets()) { if (inner instanceof EveryoneCheckbox) { everyone = ((EveryoneCheckbox) inner).isChecked(); } } final ArrayList<String> temp = new ArrayList<>(); temp.add("Everyone"); users = everyone == true ? temp : parseFieldToList(((UserField) widget).getText()); } else if (clazz.equals(CloseTimerField.class)) { try { timer = Long.parseLong(((CloseTimerField) widget).getText(), 10); } catch (Exception e) { //do nothing } } else if (clazz.equals(UseCostField.class)) { try { - cost = Double.parseDouble(((UseCostField) widget).getText()); + double value = Double.parseDouble(((UseCostField) widget).getText()); + if (value < 0) { + value = 0 - value; + } + cost = value; } catch (Exception e) { //do nothing } } else if (clazz.equals(DamageField.class)) { try { - damage = Integer.parseInt(((DamageField) widget).getText()); + int value = Integer.parseInt(((DamageField) widget).getText()); + if (value < 0) { + value = Math.abs(value); + } + damage = value; } catch (Exception e) { //do nothing } } } final Location loc = panel.getLocation(); boolean close = true; if (AqualockPlugin.getRegistry().contains(loc.getWorld().getUID(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { if (!LockUtil.update(owner, coowners, users, password, panel.getLocation(), panel.getLocation().getBlock().getData(), cost, damage, timer)) { close = false; } } else { if (!LockUtil.lock(owner, coowners, users, password, panel.getLocation(), panel.getLocation().getBlock().getData(), cost, damage, timer)) { close = false; } } if (close) { panel.close(); } } public List<String> parseFieldToList(String text) { ArrayList<String> temp = new ArrayList<>(); final char[] chars = text.toCharArray(); final StringBuilder parsed = new StringBuilder(); for (int i = 0; i < chars.length; i++) { if (chars[i] == ',') { temp.add(parsed.toString()); parsed.delete(0, parsed.length()); continue; } if (chars[i] == ' ') { continue; } if (i == chars.length) { temp.add(parsed.toString()); parsed.append(chars[i]); continue; } parsed.append(chars[i]); } return temp; } }
false
true
public void onButtonClick(ButtonClickEvent event) { final AquaPanel panel = (AquaPanel) event.getScreen(); String owner = ""; List<String> coowners = null; List<String> users = null; String password = ""; double cost = 0; int damage = 0; long timer = 0; for (Widget widget : panel.getAttachedWidgets()) { final Class clazz = widget.getClass(); if (clazz.equals(OwnerField.class)) { owner = ((OwnerField) widget).getText(); } else if (clazz.equals(PasswordField.class)) { password = ((PasswordField) widget).getText(); } else if (clazz.equals(CoOwnerField.class)) { coowners = parseFieldToList(((CoOwnerField) widget).getText()); } else if (clazz.equals(UserField.class)) { boolean everyone = false; for (Widget inner : panel.getAttachedWidgets()) { if (inner instanceof EveryoneCheckbox) { everyone = ((EveryoneCheckbox) inner).isChecked(); } } final ArrayList<String> temp = new ArrayList<>(); temp.add("Everyone"); users = everyone == true ? temp : parseFieldToList(((UserField) widget).getText()); } else if (clazz.equals(CloseTimerField.class)) { try { timer = Long.parseLong(((CloseTimerField) widget).getText(), 10); } catch (Exception e) { //do nothing } } else if (clazz.equals(UseCostField.class)) { try { cost = Double.parseDouble(((UseCostField) widget).getText()); } catch (Exception e) { //do nothing } } else if (clazz.equals(DamageField.class)) { try { damage = Integer.parseInt(((DamageField) widget).getText()); } catch (Exception e) { //do nothing } } } final Location loc = panel.getLocation(); boolean close = true; if (AqualockPlugin.getRegistry().contains(loc.getWorld().getUID(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { if (!LockUtil.update(owner, coowners, users, password, panel.getLocation(), panel.getLocation().getBlock().getData(), cost, damage, timer)) { close = false; } } else { if (!LockUtil.lock(owner, coowners, users, password, panel.getLocation(), panel.getLocation().getBlock().getData(), cost, damage, timer)) { close = false; } } if (close) { panel.close(); } }
public void onButtonClick(ButtonClickEvent event) { final AquaPanel panel = (AquaPanel) event.getScreen(); String owner = ""; List<String> coowners = null; List<String> users = null; String password = ""; double cost = 0; int damage = 0; long timer = 0; for (Widget widget : panel.getAttachedWidgets()) { final Class clazz = widget.getClass(); if (clazz.equals(OwnerField.class)) { owner = ((OwnerField) widget).getText(); } else if (clazz.equals(PasswordField.class)) { password = ((PasswordField) widget).getText(); } else if (clazz.equals(CoOwnerField.class)) { coowners = parseFieldToList(((CoOwnerField) widget).getText()); } else if (clazz.equals(UserField.class)) { boolean everyone = false; for (Widget inner : panel.getAttachedWidgets()) { if (inner instanceof EveryoneCheckbox) { everyone = ((EveryoneCheckbox) inner).isChecked(); } } final ArrayList<String> temp = new ArrayList<>(); temp.add("Everyone"); users = everyone == true ? temp : parseFieldToList(((UserField) widget).getText()); } else if (clazz.equals(CloseTimerField.class)) { try { timer = Long.parseLong(((CloseTimerField) widget).getText(), 10); } catch (Exception e) { //do nothing } } else if (clazz.equals(UseCostField.class)) { try { double value = Double.parseDouble(((UseCostField) widget).getText()); if (value < 0) { value = 0 - value; } cost = value; } catch (Exception e) { //do nothing } } else if (clazz.equals(DamageField.class)) { try { int value = Integer.parseInt(((DamageField) widget).getText()); if (value < 0) { value = Math.abs(value); } damage = value; } catch (Exception e) { //do nothing } } } final Location loc = panel.getLocation(); boolean close = true; if (AqualockPlugin.getRegistry().contains(loc.getWorld().getUID(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { if (!LockUtil.update(owner, coowners, users, password, panel.getLocation(), panel.getLocation().getBlock().getData(), cost, damage, timer)) { close = false; } } else { if (!LockUtil.lock(owner, coowners, users, password, panel.getLocation(), panel.getLocation().getBlock().getData(), cost, damage, timer)) { close = false; } } if (close) { panel.close(); } }
diff --git a/api/src/main/java/org/searchisko/api/rest/security/AuthenticationUtilService.java b/api/src/main/java/org/searchisko/api/rest/security/AuthenticationUtilService.java index 7a35144..8c1e54c 100644 --- a/api/src/main/java/org/searchisko/api/rest/security/AuthenticationUtilService.java +++ b/api/src/main/java/org/searchisko/api/rest/security/AuthenticationUtilService.java @@ -1,125 +1,125 @@ /* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. */ package org.searchisko.api.rest.security; import org.searchisko.api.annotations.security.ContributorAllowed; import org.searchisko.api.annotations.security.ProviderAllowed; import org.searchisko.api.rest.exception.NotAuthenticatedException; import org.searchisko.api.service.ContributorProfileService; import org.searchisko.api.util.SearchUtils; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.core.SecurityContext; import java.util.logging.Level; import java.util.logging.Logger; /** * Authentication utility service. Use it in your RestServices if you need info about currently logged in user! * * @author Libor Krzyzanek * @author Vlastimil Elias (velias at redhat dot com) */ @Named @RequestScoped public class AuthenticationUtilService { @Inject protected Logger log; @Inject protected ContributorProfileService contributorProfileService; /** * request scoped cache. */ private String cachedContributorId; /** * Get name of authenticated/logged in 'provider' based on security user principal. Can be used only in methods where * {@link ProviderAllowed} annotation is applied. * * @return name of authenticated provider * @throws NotAuthenticatedException if Provider is not authenticated. Use {@link ProviderAllowed} annotation to your * REST service to prevent this exception. * @see ProviderSecurityPreProcessInterceptor */ public String getAuthenticatedProvider(SecurityContext securityContext) throws NotAuthenticatedException { if (!isAuthenticatedUserOfType(securityContext, AuthenticatedUserType.PROVIDER)) { throw new NotAuthenticatedException(AuthenticatedUserType.PROVIDER); } return securityContext.getUserPrincipal().getName(); } /** * Get 'contributor id' for currently authenticated/logged in user based on security user principal. Can be used only * in methods where {@link ContributorAllowed} annotation is applied. * * @param forceCreate if <code>true</code> we need contributor id so backend should create it for logged in user if * not created yet. If <code>false</code> then we do not need it currently, so system can't create it but * return null instead. * @return contributor id - can be null if <code><forceCreate</code> is false and contributor record do not exists yet * for current user. * @throws NotAuthenticatedException in case contributor is not authenticated/logged in. This should never happen if * security interceptor is correctly implemented and configured for this class and * {@link ContributorAllowed} is used without <code>optional</code>. */ public String getAuthenticatedContributor(SecurityContext securityContext, boolean forceCreate) throws NotAuthenticatedException { - log.log(Level.FINEST, "Get Authenticated Contributor, forcCreate: {0}", forceCreate); + log.log(Level.FINEST, "Get Authenticated Contributor, forceCreate: {0}", forceCreate); if (!isAuthenticatedUserOfType(securityContext, AuthenticatedUserType.CONTRIBUTOR)) { log.fine("User is not authenticated"); cachedContributorId = null; throw new NotAuthenticatedException(AuthenticatedUserType.CONTRIBUTOR); } // cache contributor id in request not to call backend service too often if (cachedContributorId != null) return cachedContributorId; String cid = SearchUtils.trimToNull(contributorProfileService.getContributorId( securityContext.getAuthenticationScheme(), securityContext.getUserPrincipal().getName(), forceCreate)); cachedContributorId = cid; log.log(Level.FINE, "Contributor ID for authenticated user: {0}", cid); return cid; } /** * Force update of currently logged in contributor profile. No any exception is thrown. Should be called after * contributor authentication. */ public void updateAuthenticatedContributorProfile(SecurityContext securityContext) { if (isAuthenticatedUserOfType(securityContext, AuthenticatedUserType.CONTRIBUTOR)) { try { String uname = SearchUtils.trimToNull(securityContext.getUserPrincipal().getName()); if (uname != null) { // TODO CONTRIBUTOR_PROFILE we should consider to run update in another thread not to block caller contributorProfileService.createOrUpdateProfile(securityContext.getAuthenticationScheme(), uname); } } catch (Exception e) { log.log(Level.WARNING, "Contributor profile update failed: " + e.getMessage(), e); } } } /** * Check if user of given type is authenticated. * * @param userType to check * @return true if user of given type is authenticated. */ public boolean isAuthenticatedUserOfType(SecurityContext securityContext, AuthenticatedUserType userType) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Security Context: {0}, role to check: {1}", new Object[]{securityContext, userType.roleName()}); } return securityContext != null && securityContext.getUserPrincipal() != null && securityContext.isUserInRole(userType.roleName()); } }
true
true
public String getAuthenticatedContributor(SecurityContext securityContext, boolean forceCreate) throws NotAuthenticatedException { log.log(Level.FINEST, "Get Authenticated Contributor, forcCreate: {0}", forceCreate); if (!isAuthenticatedUserOfType(securityContext, AuthenticatedUserType.CONTRIBUTOR)) { log.fine("User is not authenticated"); cachedContributorId = null; throw new NotAuthenticatedException(AuthenticatedUserType.CONTRIBUTOR); } // cache contributor id in request not to call backend service too often if (cachedContributorId != null) return cachedContributorId; String cid = SearchUtils.trimToNull(contributorProfileService.getContributorId( securityContext.getAuthenticationScheme(), securityContext.getUserPrincipal().getName(), forceCreate)); cachedContributorId = cid; log.log(Level.FINE, "Contributor ID for authenticated user: {0}", cid); return cid; }
public String getAuthenticatedContributor(SecurityContext securityContext, boolean forceCreate) throws NotAuthenticatedException { log.log(Level.FINEST, "Get Authenticated Contributor, forceCreate: {0}", forceCreate); if (!isAuthenticatedUserOfType(securityContext, AuthenticatedUserType.CONTRIBUTOR)) { log.fine("User is not authenticated"); cachedContributorId = null; throw new NotAuthenticatedException(AuthenticatedUserType.CONTRIBUTOR); } // cache contributor id in request not to call backend service too often if (cachedContributorId != null) return cachedContributorId; String cid = SearchUtils.trimToNull(contributorProfileService.getContributorId( securityContext.getAuthenticationScheme(), securityContext.getUserPrincipal().getName(), forceCreate)); cachedContributorId = cid; log.log(Level.FINE, "Contributor ID for authenticated user: {0}", cid); return cid; }
diff --git a/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/TextBox.java b/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/TextBox.java index e534587..edcf7ca 100644 --- a/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/TextBox.java +++ b/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/TextBox.java @@ -1,260 +1,260 @@ package com.eagerlogic.cubee.client.components; import com.eagerlogic.cubee.client.EventQueue; import com.eagerlogic.cubee.client.properties.BackgroundProperty; import com.eagerlogic.cubee.client.properties.BooleanProperty; import com.eagerlogic.cubee.client.properties.BorderProperty; import com.eagerlogic.cubee.client.properties.ColorProperty; import com.eagerlogic.cubee.client.properties.IChangeListener; import com.eagerlogic.cubee.client.properties.IntegerProperty; import com.eagerlogic.cubee.client.properties.PaddingProperty; import com.eagerlogic.cubee.client.properties.Property; import com.eagerlogic.cubee.client.properties.StringProperty; import com.eagerlogic.cubee.client.styles.Color; import com.eagerlogic.cubee.client.styles.ColorBackground; import com.eagerlogic.cubee.client.styles.ETextAlign; import com.eagerlogic.cubee.client.styles.EVAlign; import com.eagerlogic.cubee.client.styles.FontFamily; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.EventListener; /** * * @author dipacs */ public class TextBox extends AComponent { private final IntegerProperty width = new IntegerProperty(null, true, false); private final IntegerProperty height = new IntegerProperty(null, true, false); private final StringProperty text = new StringProperty("", false, false); private final BackgroundProperty background = new BackgroundProperty(new ColorBackground(Color.WHITE), true, false); private final ColorProperty foreColor = new ColorProperty(Color.BLACK, true, false); private final Property<ETextAlign> textAlign = new Property<ETextAlign>(ETextAlign.LEFT, false, false); private final Property<EVAlign> verticalAlign = new Property<EVAlign>(EVAlign.TOP, false, false); private final BooleanProperty bold = new BooleanProperty(false, false, false); private final BooleanProperty italic = new BooleanProperty(false, false, false); private final BooleanProperty underline = new BooleanProperty(false, false, false); private final IntegerProperty fontSize = new IntegerProperty(12, false, false); private final Property<FontFamily> fontFamily = new Property<FontFamily>(FontFamily.Arial, false, false); public TextBox() { this(DOM.createInputText()); } TextBox(Element e) { super(e); width.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (width.get() == null) { getElement().getStyle().clearWidth(); getElement().getStyle().setOverflowX(Style.Overflow.AUTO); } else { getElement().getStyle().setWidth(width.get(), Style.Unit.PX); getElement().getStyle().setOverflowX(Style.Overflow.HIDDEN); } requestLayout(); } }); height.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (height.get() == null) { getElement().getStyle().clearHeight(); getElement().getStyle().setOverflowY(Style.Overflow.AUTO); } else { getElement().getStyle().setHeight(height.get(), Style.Unit.PX); getElement().getStyle().setOverflowY(Style.Overflow.HIDDEN); } requestLayout(); } }); text.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { - getElement().setAttribute("value", text.get()); + getElement().setPropertyString("value", text.get()); } }); foreColor.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (foreColor.get() == null) { getElement().getStyle().setColor("rgba(0, 0, 0, 0.0)"); } else { getElement().getStyle().setColor(foreColor.get().toCSS()); } } }); foreColor.invalidate(); textAlign.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { textAlign.get().apply(getElement()); } }); textAlign.invalidate(); verticalAlign.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { EVAlign ta = verticalAlign.get(); if (ta == EVAlign.TOP) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.TOP); } else if (ta == EVAlign.MIDDLE) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.MIDDLE); } else if (ta == EVAlign.BOTTOM) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.BOTTOM); } } }); verticalAlign.invalidate(); underline.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (underline.get()) { getElement().getStyle().setTextDecoration(Style.TextDecoration.UNDERLINE); } else { getElement().getStyle().setTextDecoration(Style.TextDecoration.NONE); } requestLayout(); } }); underline.invalidate(); bold.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (bold.get()) { getElement().getStyle().setFontWeight(Style.FontWeight.BOLD); } else { getElement().getStyle().setFontWeight(Style.FontWeight.NORMAL); } requestLayout(); } }); bold.invalidate(); italic.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (italic.get()) { getElement().getStyle().setFontStyle(Style.FontStyle.ITALIC); } else { getElement().getStyle().setFontStyle(Style.FontStyle.NORMAL); } requestLayout(); } }); italic.invalidate(); fontSize.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { getElement().getStyle().setFontSize(fontSize.get(), Style.Unit.PX); requestLayout(); } }); fontSize.invalidate(); fontFamily.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { fontFamily.get().apply(getElement()); requestLayout(); } }); fontFamily.invalidate(); DOM.setEventListener((com.google.gwt.user.client.Element)getElement(), new EventListener() { @Override public void onBrowserEvent(com.google.gwt.user.client.Event event) { if ((event.getTypeInt() & com.google.gwt.user.client.Event.ONKEYUP) > 0) { EventQueue.getInstance().invokePrior(new Runnable() { @Override public void run() { text.set(getElement().getPropertyString("value")); } }); } } }); background.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (background.get() == null) { // TODO clear background } else { background.get().apply(getElement()); } } }); background.invalidate(); } public final IntegerProperty widthProperty() { return width; } public final IntegerProperty heightProperty() { return height; } @Override public final PaddingProperty paddingProperty() { return super.paddingProperty(); } @Override public final BorderProperty borderProperty() { return super.borderProperty(); } public final StringProperty textProperty() { return text; } public final BackgroundProperty backgroundProperty() { return background; } public final ColorProperty foreColorProperty() { return foreColor; } public final Property<ETextAlign> textAlignProperty() { return textAlign; } public final Property<EVAlign> verticalAlignProperty() { return verticalAlign; } public final BooleanProperty boldProperty() { return bold; } public final BooleanProperty italicProperty() { return italic; } public final BooleanProperty underlineProperty() { return underline; } public final IntegerProperty fontSizeProperty() { return fontSize; } public final Property<FontFamily> fontFamilyProperty() { return fontFamily; } }
true
true
TextBox(Element e) { super(e); width.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (width.get() == null) { getElement().getStyle().clearWidth(); getElement().getStyle().setOverflowX(Style.Overflow.AUTO); } else { getElement().getStyle().setWidth(width.get(), Style.Unit.PX); getElement().getStyle().setOverflowX(Style.Overflow.HIDDEN); } requestLayout(); } }); height.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (height.get() == null) { getElement().getStyle().clearHeight(); getElement().getStyle().setOverflowY(Style.Overflow.AUTO); } else { getElement().getStyle().setHeight(height.get(), Style.Unit.PX); getElement().getStyle().setOverflowY(Style.Overflow.HIDDEN); } requestLayout(); } }); text.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { getElement().setAttribute("value", text.get()); } }); foreColor.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (foreColor.get() == null) { getElement().getStyle().setColor("rgba(0, 0, 0, 0.0)"); } else { getElement().getStyle().setColor(foreColor.get().toCSS()); } } }); foreColor.invalidate(); textAlign.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { textAlign.get().apply(getElement()); } }); textAlign.invalidate(); verticalAlign.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { EVAlign ta = verticalAlign.get(); if (ta == EVAlign.TOP) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.TOP); } else if (ta == EVAlign.MIDDLE) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.MIDDLE); } else if (ta == EVAlign.BOTTOM) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.BOTTOM); } } }); verticalAlign.invalidate(); underline.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (underline.get()) { getElement().getStyle().setTextDecoration(Style.TextDecoration.UNDERLINE); } else { getElement().getStyle().setTextDecoration(Style.TextDecoration.NONE); } requestLayout(); } }); underline.invalidate(); bold.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (bold.get()) { getElement().getStyle().setFontWeight(Style.FontWeight.BOLD); } else { getElement().getStyle().setFontWeight(Style.FontWeight.NORMAL); } requestLayout(); } }); bold.invalidate(); italic.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (italic.get()) { getElement().getStyle().setFontStyle(Style.FontStyle.ITALIC); } else { getElement().getStyle().setFontStyle(Style.FontStyle.NORMAL); } requestLayout(); } }); italic.invalidate(); fontSize.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { getElement().getStyle().setFontSize(fontSize.get(), Style.Unit.PX); requestLayout(); } }); fontSize.invalidate(); fontFamily.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { fontFamily.get().apply(getElement()); requestLayout(); } }); fontFamily.invalidate(); DOM.setEventListener((com.google.gwt.user.client.Element)getElement(), new EventListener() { @Override public void onBrowserEvent(com.google.gwt.user.client.Event event) { if ((event.getTypeInt() & com.google.gwt.user.client.Event.ONKEYUP) > 0) { EventQueue.getInstance().invokePrior(new Runnable() { @Override public void run() { text.set(getElement().getPropertyString("value")); } }); } } }); background.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (background.get() == null) { // TODO clear background } else { background.get().apply(getElement()); } } }); background.invalidate(); }
TextBox(Element e) { super(e); width.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (width.get() == null) { getElement().getStyle().clearWidth(); getElement().getStyle().setOverflowX(Style.Overflow.AUTO); } else { getElement().getStyle().setWidth(width.get(), Style.Unit.PX); getElement().getStyle().setOverflowX(Style.Overflow.HIDDEN); } requestLayout(); } }); height.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (height.get() == null) { getElement().getStyle().clearHeight(); getElement().getStyle().setOverflowY(Style.Overflow.AUTO); } else { getElement().getStyle().setHeight(height.get(), Style.Unit.PX); getElement().getStyle().setOverflowY(Style.Overflow.HIDDEN); } requestLayout(); } }); text.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { getElement().setPropertyString("value", text.get()); } }); foreColor.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (foreColor.get() == null) { getElement().getStyle().setColor("rgba(0, 0, 0, 0.0)"); } else { getElement().getStyle().setColor(foreColor.get().toCSS()); } } }); foreColor.invalidate(); textAlign.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { textAlign.get().apply(getElement()); } }); textAlign.invalidate(); verticalAlign.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { EVAlign ta = verticalAlign.get(); if (ta == EVAlign.TOP) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.TOP); } else if (ta == EVAlign.MIDDLE) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.MIDDLE); } else if (ta == EVAlign.BOTTOM) { getElement().getStyle().setVerticalAlign(Style.VerticalAlign.BOTTOM); } } }); verticalAlign.invalidate(); underline.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (underline.get()) { getElement().getStyle().setTextDecoration(Style.TextDecoration.UNDERLINE); } else { getElement().getStyle().setTextDecoration(Style.TextDecoration.NONE); } requestLayout(); } }); underline.invalidate(); bold.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (bold.get()) { getElement().getStyle().setFontWeight(Style.FontWeight.BOLD); } else { getElement().getStyle().setFontWeight(Style.FontWeight.NORMAL); } requestLayout(); } }); bold.invalidate(); italic.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (italic.get()) { getElement().getStyle().setFontStyle(Style.FontStyle.ITALIC); } else { getElement().getStyle().setFontStyle(Style.FontStyle.NORMAL); } requestLayout(); } }); italic.invalidate(); fontSize.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { getElement().getStyle().setFontSize(fontSize.get(), Style.Unit.PX); requestLayout(); } }); fontSize.invalidate(); fontFamily.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { fontFamily.get().apply(getElement()); requestLayout(); } }); fontFamily.invalidate(); DOM.setEventListener((com.google.gwt.user.client.Element)getElement(), new EventListener() { @Override public void onBrowserEvent(com.google.gwt.user.client.Event event) { if ((event.getTypeInt() & com.google.gwt.user.client.Event.ONKEYUP) > 0) { EventQueue.getInstance().invokePrior(new Runnable() { @Override public void run() { text.set(getElement().getPropertyString("value")); } }); } } }); background.addChangeListener(new IChangeListener() { @Override public void onChanged(Object sender) { if (background.get() == null) { // TODO clear background } else { background.get().apply(getElement()); } } }); background.invalidate(); }
diff --git a/src/main/java/org/atlasapi/remotesite/ContentMerger.java b/src/main/java/org/atlasapi/remotesite/ContentMerger.java index 0fe6dc093..f60318414 100644 --- a/src/main/java/org/atlasapi/remotesite/ContentMerger.java +++ b/src/main/java/org/atlasapi/remotesite/ContentMerger.java @@ -1,69 +1,70 @@ package org.atlasapi.remotesite; import org.atlasapi.media.entity.Container; import org.atlasapi.media.entity.Content; import org.atlasapi.media.entity.Episode; import org.atlasapi.media.entity.Identified; import org.atlasapi.media.entity.Item; import org.atlasapi.media.entity.Series; public class ContentMerger { public static Item merge(Item current, Item extracted) { current = mergeContents(current, extracted); current.setParentRef(extracted.getContainer()); current.setVersions(extracted.getVersions()); if (current instanceof Episode && extracted instanceof Episode) { Episode currentEp = (Episode) current; Episode extractedEp = (Episode) extracted; currentEp.setEpisodeNumber(extractedEp.getEpisodeNumber()); currentEp.setSeriesRef(extractedEp.getSeriesRef()); } return current; } public static Container merge(Container current, Container extracted) { current = mergeContents(current, extracted); if (current instanceof Series && extracted instanceof Series) { ((Series) current).withSeriesNumber(((Series) extracted).getSeriesNumber()); ((Series) current).setParentRef(((Series) extracted).getParent()); } return current; } private static <C extends Content> C mergeContents(C current, C extracted) { current.setActivelyPublished(extracted.isActivelyPublished()); current.setAliasUrls(extracted.getAliasUrls()); + current.setAliases(extracted.getAliases()); current.setTitle(extracted.getTitle()); current.setDescription(extracted.getDescription()); current.setImage(extracted.getImage()); current.setYear(extracted.getYear()); current.setGenres(extracted.getGenres()); current.setPeople(extracted.people()); current.setLanguages(extracted.getLanguages()); current.setCertificates(extracted.getCertificates()); current.setMediaType(extracted.getMediaType()); current.setSpecialization(extracted.getSpecialization()); current.setLastUpdated(extracted.getLastUpdated()); return current; } public static Container asContainer(Identified identified) { return castTo(identified, Container.class); } public static Item asItem(Identified identified) { return castTo(identified, Item.class); } private static <T> T castTo(Identified identified, Class<T> cls) { try { return cls.cast(identified); } catch (ClassCastException e) { throw new ClassCastException(String.format("%s: expected %s got %s", identified.getCanonicalUri(), cls.getSimpleName(), identified.getClass().getSimpleName())); } } }
true
true
private static <C extends Content> C mergeContents(C current, C extracted) { current.setActivelyPublished(extracted.isActivelyPublished()); current.setAliasUrls(extracted.getAliasUrls()); current.setTitle(extracted.getTitle()); current.setDescription(extracted.getDescription()); current.setImage(extracted.getImage()); current.setYear(extracted.getYear()); current.setGenres(extracted.getGenres()); current.setPeople(extracted.people()); current.setLanguages(extracted.getLanguages()); current.setCertificates(extracted.getCertificates()); current.setMediaType(extracted.getMediaType()); current.setSpecialization(extracted.getSpecialization()); current.setLastUpdated(extracted.getLastUpdated()); return current; }
private static <C extends Content> C mergeContents(C current, C extracted) { current.setActivelyPublished(extracted.isActivelyPublished()); current.setAliasUrls(extracted.getAliasUrls()); current.setAliases(extracted.getAliases()); current.setTitle(extracted.getTitle()); current.setDescription(extracted.getDescription()); current.setImage(extracted.getImage()); current.setYear(extracted.getYear()); current.setGenres(extracted.getGenres()); current.setPeople(extracted.people()); current.setLanguages(extracted.getLanguages()); current.setCertificates(extracted.getCertificates()); current.setMediaType(extracted.getMediaType()); current.setSpecialization(extracted.getSpecialization()); current.setLastUpdated(extracted.getLastUpdated()); return current; }
diff --git a/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java b/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java index a999224..460a1de 100644 --- a/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java +++ b/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java @@ -1,195 +1,196 @@ /* * * * Copyright - TrianaCloud * * Copyright (C) 2012. Kieran Evans. All Rights Reserved. * * * * 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 2 * * 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, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package org.trianacode.TrianaCloud.Worker; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; import org.apache.log4j.Logger; import org.trianacode.TrianaCloud.Utils.Task; import org.trianacode.TrianaCloud.Utils.TaskExecutor; import org.trianacode.TrianaCloud.Utils.TaskExecutorLoader; import org.trianacode.TrianaCloud.Utils.TaskOps; import java.io.File; import java.net.MalformedURLException; import java.net.URL; /** * @author Kieran David Evans * @version 1.0.0 Feb 26, 2012 */ /* * The worker looks for tasks, and executes them. Easy. */ public class Worker { private Logger logger = Logger.getLogger(this.getClass().toString()); private static boolean continueLoop = true; private static TaskExecutorLoader tel; public static void main(String[] argv) { Connection connection = null; Channel channel; try { loadPlugins(argv); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("s-vmc.cs.cf.ac.uk"); factory.setPort(7000); factory.setUsername("trianacloud"); factory.setPassword("trianacloud"); + factory.setRequestedHeartbeat(60); connection = factory.newConnection(); channel = connection.createChannel(); //Use tc_exchange (TrianaCloud_exchange) in the topic config. ///TODO:Grab this from argv or config file channel.exchangeDeclare("tc_exchange", "topic"); /* "dart.triana" is the queue name. If the task is covered by multiple topic bindings, it's duplicated. If there are multiple queues for a topic binding, it's duplicated. This could be useful for debugging, logging and auditing. This could also be used to implement validation, which inherently ensures that the two (or more) duplicate tasks to compare and validate aren't executed on the same machine. But for a standard single worker, single task config, follow the rule of thumb. Rule of thumb: if the topic binding is the same, the queue name should be the same. If you're using wildcards in a topic name, MAKE SURE other topics/queues don't collide. e.g.: BAD: dart.triana on worker1 #.triana on worker2 GOOD: dart.eddie.triana (this will grab those with this exact topic) *.triana (* substitutes exactly one word. dart.eddie.triana ISN'T caught) */ //String routingKey = "*.kieran"; // String routingKey = "*.triana"; QueueingConsumer consumer = new QueueingConsumer(channel); for (String routingKey : tel.routingKeys) { System.out.println(" [x] Routing Key: " + routingKey); ///TODO:Grab from argv or config file String queueName = channel.queueDeclare(routingKey, true, false, true, null).getQueue(); channel.queueBind(queueName, "tc_exchange", routingKey); //Makes sure tasks are shared properly, this tells rabbit to only grab one message at a time. channel.basicQos(1); channel.basicConsume(queueName, false, consumer); } System.out.println(" [x] Awaiting RPC requests"); while (continueLoop) { byte[] response = new byte[0]; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties .Builder() .correlationId(props.getCorrelationId()) .build(); TaskExecutor ex; try { ///TODO: Use metadata to figure out which Executor to use. ///TODO: Figure out what wire-protocol to use. Something simple like ASN.1? Or a subset of it? //String message = new String(delivery.getBody()); byte[] message = delivery.getBody(); ex = tel.getExecutor("org.trianacode.TrianaCloud.TrianaTaskExecutor.Executor"); //TaskExecutor ex = tel.getExecutor("org.trianacode.TrianaCloud.CommandLineExecutor.Executor"); Task t = TaskOps.decodeTask(message); ex.setTask(t); response = ex.executeTask(); } catch (Exception e) { ///TODO: filter the errors. Worker errors should skip the Ack, and allow the task to be redone. ///TODO: Two new exeptions for the task executor, one to indicate that the execution failed due to /// the data, one to indicate some other error. The former would be ack'ed and sent back, as /// it's a user error (i.e. the data is bad). The latter would indicate any other errors (bad /// config, random error, missile strike). System.out.println(" [.] " + e.toString()); e.printStackTrace(); response = new byte[0]; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response); //Acknowledge that the task has been received. If a crash happens before here, then Rabbit automagically //sticks the message back in the queue. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //TODO bye bye!! // System.exit(0); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } } private static void loadPlugins(String[] argv) throws MalformedURLException { System.out.println(" [x] Loading Plugins"); ClassLoader classLoader = Worker.class.getClassLoader(); ///TODO:Make sure there's not a better way to do this URL[] urls = new URL[1]; ///TODO:Grab a plugin dir from the config file String workingDir; File f; if (argv.length > 0) { workingDir = argv[0]; f = new File(workingDir); } else { workingDir = System.getProperty("user.dir"); f = new File(workingDir + File.separator + "depsdir"); } System.out.println("Addon path : " + f.getAbsolutePath()); urls[0] = f.toURI().toURL(); //Load plugins using the fancy-pants loader hacked together using the code from iharvey and the intarwebs tel = new TaskExecutorLoader(urls, classLoader); } }
true
true
public static void main(String[] argv) { Connection connection = null; Channel channel; try { loadPlugins(argv); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("s-vmc.cs.cf.ac.uk"); factory.setPort(7000); factory.setUsername("trianacloud"); factory.setPassword("trianacloud"); connection = factory.newConnection(); channel = connection.createChannel(); //Use tc_exchange (TrianaCloud_exchange) in the topic config. ///TODO:Grab this from argv or config file channel.exchangeDeclare("tc_exchange", "topic"); /* "dart.triana" is the queue name. If the task is covered by multiple topic bindings, it's duplicated. If there are multiple queues for a topic binding, it's duplicated. This could be useful for debugging, logging and auditing. This could also be used to implement validation, which inherently ensures that the two (or more) duplicate tasks to compare and validate aren't executed on the same machine. But for a standard single worker, single task config, follow the rule of thumb. Rule of thumb: if the topic binding is the same, the queue name should be the same. If you're using wildcards in a topic name, MAKE SURE other topics/queues don't collide. e.g.: BAD: dart.triana on worker1 #.triana on worker2 GOOD: dart.eddie.triana (this will grab those with this exact topic) *.triana (* substitutes exactly one word. dart.eddie.triana ISN'T caught) */ //String routingKey = "*.kieran"; // String routingKey = "*.triana"; QueueingConsumer consumer = new QueueingConsumer(channel); for (String routingKey : tel.routingKeys) { System.out.println(" [x] Routing Key: " + routingKey); ///TODO:Grab from argv or config file String queueName = channel.queueDeclare(routingKey, true, false, true, null).getQueue(); channel.queueBind(queueName, "tc_exchange", routingKey); //Makes sure tasks are shared properly, this tells rabbit to only grab one message at a time. channel.basicQos(1); channel.basicConsume(queueName, false, consumer); } System.out.println(" [x] Awaiting RPC requests"); while (continueLoop) { byte[] response = new byte[0]; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties .Builder() .correlationId(props.getCorrelationId()) .build(); TaskExecutor ex; try { ///TODO: Use metadata to figure out which Executor to use. ///TODO: Figure out what wire-protocol to use. Something simple like ASN.1? Or a subset of it? //String message = new String(delivery.getBody()); byte[] message = delivery.getBody(); ex = tel.getExecutor("org.trianacode.TrianaCloud.TrianaTaskExecutor.Executor"); //TaskExecutor ex = tel.getExecutor("org.trianacode.TrianaCloud.CommandLineExecutor.Executor"); Task t = TaskOps.decodeTask(message); ex.setTask(t); response = ex.executeTask(); } catch (Exception e) { ///TODO: filter the errors. Worker errors should skip the Ack, and allow the task to be redone. ///TODO: Two new exeptions for the task executor, one to indicate that the execution failed due to /// the data, one to indicate some other error. The former would be ack'ed and sent back, as /// it's a user error (i.e. the data is bad). The latter would indicate any other errors (bad /// config, random error, missile strike). System.out.println(" [.] " + e.toString()); e.printStackTrace(); response = new byte[0]; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response); //Acknowledge that the task has been received. If a crash happens before here, then Rabbit automagically //sticks the message back in the queue. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //TODO bye bye!! // System.exit(0); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
public static void main(String[] argv) { Connection connection = null; Channel channel; try { loadPlugins(argv); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("s-vmc.cs.cf.ac.uk"); factory.setPort(7000); factory.setUsername("trianacloud"); factory.setPassword("trianacloud"); factory.setRequestedHeartbeat(60); connection = factory.newConnection(); channel = connection.createChannel(); //Use tc_exchange (TrianaCloud_exchange) in the topic config. ///TODO:Grab this from argv or config file channel.exchangeDeclare("tc_exchange", "topic"); /* "dart.triana" is the queue name. If the task is covered by multiple topic bindings, it's duplicated. If there are multiple queues for a topic binding, it's duplicated. This could be useful for debugging, logging and auditing. This could also be used to implement validation, which inherently ensures that the two (or more) duplicate tasks to compare and validate aren't executed on the same machine. But for a standard single worker, single task config, follow the rule of thumb. Rule of thumb: if the topic binding is the same, the queue name should be the same. If you're using wildcards in a topic name, MAKE SURE other topics/queues don't collide. e.g.: BAD: dart.triana on worker1 #.triana on worker2 GOOD: dart.eddie.triana (this will grab those with this exact topic) *.triana (* substitutes exactly one word. dart.eddie.triana ISN'T caught) */ //String routingKey = "*.kieran"; // String routingKey = "*.triana"; QueueingConsumer consumer = new QueueingConsumer(channel); for (String routingKey : tel.routingKeys) { System.out.println(" [x] Routing Key: " + routingKey); ///TODO:Grab from argv or config file String queueName = channel.queueDeclare(routingKey, true, false, true, null).getQueue(); channel.queueBind(queueName, "tc_exchange", routingKey); //Makes sure tasks are shared properly, this tells rabbit to only grab one message at a time. channel.basicQos(1); channel.basicConsume(queueName, false, consumer); } System.out.println(" [x] Awaiting RPC requests"); while (continueLoop) { byte[] response = new byte[0]; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties .Builder() .correlationId(props.getCorrelationId()) .build(); TaskExecutor ex; try { ///TODO: Use metadata to figure out which Executor to use. ///TODO: Figure out what wire-protocol to use. Something simple like ASN.1? Or a subset of it? //String message = new String(delivery.getBody()); byte[] message = delivery.getBody(); ex = tel.getExecutor("org.trianacode.TrianaCloud.TrianaTaskExecutor.Executor"); //TaskExecutor ex = tel.getExecutor("org.trianacode.TrianaCloud.CommandLineExecutor.Executor"); Task t = TaskOps.decodeTask(message); ex.setTask(t); response = ex.executeTask(); } catch (Exception e) { ///TODO: filter the errors. Worker errors should skip the Ack, and allow the task to be redone. ///TODO: Two new exeptions for the task executor, one to indicate that the execution failed due to /// the data, one to indicate some other error. The former would be ack'ed and sent back, as /// it's a user error (i.e. the data is bad). The latter would indicate any other errors (bad /// config, random error, missile strike). System.out.println(" [.] " + e.toString()); e.printStackTrace(); response = new byte[0]; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response); //Acknowledge that the task has been received. If a crash happens before here, then Rabbit automagically //sticks the message back in the queue. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //TODO bye bye!! // System.exit(0); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
diff --git a/src/main/java/nl/mdlware/confluence/plugins/citation/XMLDocumentWrapper.java b/src/main/java/nl/mdlware/confluence/plugins/citation/XMLDocumentWrapper.java index 63a4788..3e08a65 100644 --- a/src/main/java/nl/mdlware/confluence/plugins/citation/XMLDocumentWrapper.java +++ b/src/main/java/nl/mdlware/confluence/plugins/citation/XMLDocumentWrapper.java @@ -1,7 +1,7 @@ package nl.mdlware.confluence.plugins.citation; public class XMLDocumentWrapper { public static String wrapIntoValidXML(String pageContents) { - return "<?xml version=\"1.0\"?><!DOCTYPE some_name [<!ENTITY nbsp \"&#160;\">]><p>" + pageContents + "</p>"; + return "<?xml version=\"1.0\"?><!DOCTYPE some_name [<!ENTITY nbsp \"&#160;\"><!ENTITY ndash \"&#8211;\"><!ENTITY mdash \"&#8212;\"><!ENTITY rsquo \"&#8217;\"> ]><p>" + pageContents + "</p>"; } }
true
true
public static String wrapIntoValidXML(String pageContents) { return "<?xml version=\"1.0\"?><!DOCTYPE some_name [<!ENTITY nbsp \"&#160;\">]><p>" + pageContents + "</p>"; }
public static String wrapIntoValidXML(String pageContents) { return "<?xml version=\"1.0\"?><!DOCTYPE some_name [<!ENTITY nbsp \"&#160;\"><!ENTITY ndash \"&#8211;\"><!ENTITY mdash \"&#8212;\"><!ENTITY rsquo \"&#8217;\"> ]><p>" + pageContents + "</p>"; }
diff --git a/MazeGame/src/mapMaker/ControlsPanel.java b/MazeGame/src/mapMaker/ControlsPanel.java index 6d1b967..d49b3fb 100644 --- a/MazeGame/src/mapMaker/ControlsPanel.java +++ b/MazeGame/src/mapMaker/ControlsPanel.java @@ -1,57 +1,58 @@ package mapMaker; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import javax.swing.JPanel; public class ControlsPanel extends JPanel { private static final long serialVersionUID = 1L; private String blankButton = "Blank (b)"; private String endButton = "End (e)"; private String grassButton = "Grass (g)"; private String startButton = "Start (s)"; private String wallButton = "Wall (w)"; private String saveButton = "Save (C-S)"; private String deco1Button = "Deco1 (1)"; private String deco2Button = "Deco1 (2)"; private String deco3Button = "Deco1 (3)"; private String deco4Button = "Deco1 (4)"; private String deco5Button = "Deco1 (5)"; public static String saveMessage = "", saveTime = ""; private Font font1 = new Font("Arial", Font.PLAIN, 15); public ControlsPanel() { setPreferredSize(new Dimension(3 * 32 + 6, Board.height)); } public void paint(Graphics g) { super.paint(g); int ix = 0; g.setFont(font1); g.setColor(Color.black); g.drawString(blankButton, 5, ix += 25); g.drawString(endButton, 5, ix += 25); g.drawString(grassButton, 5, ix += 25); g.drawString(startButton, 5, ix += 25); g.drawString(wallButton, 5, ix += 25); g.drawString(deco1Button, 5, ix += 50); g.drawString(deco2Button, 5, ix += 25); g.drawString(deco3Button, 5, ix += 25); g.drawString(deco4Button, 5, ix += 25); g.drawString(deco5Button, 5, ix += 25); g.drawString(saveButton, 5, ix += 50); g.drawString(saveMessage, 5, ix += 50); g.drawString(saveTime, 5, ix += 20); + repaint(); } }
true
true
public void paint(Graphics g) { super.paint(g); int ix = 0; g.setFont(font1); g.setColor(Color.black); g.drawString(blankButton, 5, ix += 25); g.drawString(endButton, 5, ix += 25); g.drawString(grassButton, 5, ix += 25); g.drawString(startButton, 5, ix += 25); g.drawString(wallButton, 5, ix += 25); g.drawString(deco1Button, 5, ix += 50); g.drawString(deco2Button, 5, ix += 25); g.drawString(deco3Button, 5, ix += 25); g.drawString(deco4Button, 5, ix += 25); g.drawString(deco5Button, 5, ix += 25); g.drawString(saveButton, 5, ix += 50); g.drawString(saveMessage, 5, ix += 50); g.drawString(saveTime, 5, ix += 20); }
public void paint(Graphics g) { super.paint(g); int ix = 0; g.setFont(font1); g.setColor(Color.black); g.drawString(blankButton, 5, ix += 25); g.drawString(endButton, 5, ix += 25); g.drawString(grassButton, 5, ix += 25); g.drawString(startButton, 5, ix += 25); g.drawString(wallButton, 5, ix += 25); g.drawString(deco1Button, 5, ix += 50); g.drawString(deco2Button, 5, ix += 25); g.drawString(deco3Button, 5, ix += 25); g.drawString(deco4Button, 5, ix += 25); g.drawString(deco5Button, 5, ix += 25); g.drawString(saveButton, 5, ix += 50); g.drawString(saveMessage, 5, ix += 50); g.drawString(saveTime, 5, ix += 20); repaint(); }
diff --git a/activeweb/src/test/java/org/javalite/activeweb/EncodingSpec.java b/activeweb/src/test/java/org/javalite/activeweb/EncodingSpec.java index 09973e1..7d8110b 100644 --- a/activeweb/src/test/java/org/javalite/activeweb/EncodingSpec.java +++ b/activeweb/src/test/java/org/javalite/activeweb/EncodingSpec.java @@ -1,33 +1,33 @@ package org.javalite.activeweb; import org.junit.Test; import javax.servlet.ServletException; import java.io.IOException; /** * @author Igor Polevoy: 7/23/12 2:32 PM */ public class EncodingSpec extends RequestSpec { @Test public void shouldShouldOverrideEncodingInController() throws IOException, ServletException { request.setServletPath("/encoding"); request.setMethod("GET"); dispatcher.doFilter(request, response, filterChain); a(response.getContentAsString()).shouldBeEqual("hi"); a(response.getCharacterEncoding()).shouldBeEqual("UTF-8"); } @Test public void shouldShouldOverrideControllerEncodingWithActionEncoding() throws IOException, ServletException { request.setServletPath("/encoding2"); request.setMethod("GET"); dispatcher.doFilter(request, response, filterChain); a(response.getContentAsString()).shouldBeEqual("hi"); - a(response.getCharacterEncoding()).shouldBeEqual("UTF-16"); + a(response.getCharacterEncoding()).shouldBeEqual("UTF-8"); } }
true
true
public void shouldShouldOverrideControllerEncodingWithActionEncoding() throws IOException, ServletException { request.setServletPath("/encoding2"); request.setMethod("GET"); dispatcher.doFilter(request, response, filterChain); a(response.getContentAsString()).shouldBeEqual("hi"); a(response.getCharacterEncoding()).shouldBeEqual("UTF-16"); }
public void shouldShouldOverrideControllerEncodingWithActionEncoding() throws IOException, ServletException { request.setServletPath("/encoding2"); request.setMethod("GET"); dispatcher.doFilter(request, response, filterChain); a(response.getContentAsString()).shouldBeEqual("hi"); a(response.getCharacterEncoding()).shouldBeEqual("UTF-8"); }
diff --git a/src/main/java/com/github/ucchyocean/cmt/command/CRemoveCommand.java b/src/main/java/com/github/ucchyocean/cmt/command/CRemoveCommand.java index ca6c722..d153faf 100644 --- a/src/main/java/com/github/ucchyocean/cmt/command/CRemoveCommand.java +++ b/src/main/java/com/github/ucchyocean/cmt/command/CRemoveCommand.java @@ -1,44 +1,44 @@ /* * Copyright ucchy 2013 */ package com.github.ucchyocean.cmt.command; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import com.github.ucchyocean.cmt.ColorMeTeamingConfig; /** * @author ucchy * CRemove(CR)コマンドの実行クラス */ public class CRemoveCommand implements CommandExecutor { /** * @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) */ public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if ( args.length <= 0 ) { return false; } if ( args[0].equalsIgnoreCase("on") ) { ColorMeTeamingConfig.autoColorRemove = true; sender.sendMessage(ChatColor.GRAY + "死亡時のチーム離脱が有効になりました。"); - ColorMeTeamingConfig.setConfigValue("firelyFireDisabler", true); + ColorMeTeamingConfig.setConfigValue("autoColorRemove", true); return true; } else if ( args[0].equalsIgnoreCase("off") ) { ColorMeTeamingConfig.autoColorRemove = false; sender.sendMessage(ChatColor.GRAY + "死亡時のチーム離脱が無効になりました。"); - ColorMeTeamingConfig.setConfigValue("firelyFireDisabler", false); + ColorMeTeamingConfig.setConfigValue("autoColorRemove", false); return true; } return false; } }
false
true
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if ( args.length <= 0 ) { return false; } if ( args[0].equalsIgnoreCase("on") ) { ColorMeTeamingConfig.autoColorRemove = true; sender.sendMessage(ChatColor.GRAY + "死亡時のチーム離脱が有効になりました。"); ColorMeTeamingConfig.setConfigValue("firelyFireDisabler", true); return true; } else if ( args[0].equalsIgnoreCase("off") ) { ColorMeTeamingConfig.autoColorRemove = false; sender.sendMessage(ChatColor.GRAY + "死亡時のチーム離脱が無効になりました。"); ColorMeTeamingConfig.setConfigValue("firelyFireDisabler", false); return true; } return false; }
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if ( args.length <= 0 ) { return false; } if ( args[0].equalsIgnoreCase("on") ) { ColorMeTeamingConfig.autoColorRemove = true; sender.sendMessage(ChatColor.GRAY + "死亡時のチーム離脱が有効になりました。"); ColorMeTeamingConfig.setConfigValue("autoColorRemove", true); return true; } else if ( args[0].equalsIgnoreCase("off") ) { ColorMeTeamingConfig.autoColorRemove = false; sender.sendMessage(ChatColor.GRAY + "死亡時のチーム離脱が無効になりました。"); ColorMeTeamingConfig.setConfigValue("autoColorRemove", false); return true; } return false; }
diff --git a/jRealityPlugin/src/de/tum/in/jrealityplugin/jogl/Util.java b/jRealityPlugin/src/de/tum/in/jrealityplugin/jogl/Util.java index e444d17..db23c7e 100644 --- a/jRealityPlugin/src/de/tum/in/jrealityplugin/jogl/Util.java +++ b/jRealityPlugin/src/de/tum/in/jrealityplugin/jogl/Util.java @@ -1,25 +1,25 @@ package de.tum.in.jrealityplugin.jogl; import javax.vecmath.AxisAngle4d; import javax.vecmath.Matrix4d; import javax.vecmath.Vector3d; public class Util { public static AxisAngle4d rotateFromTo(Vector3d from, Vector3d to) { double angle = from.angle(to); - if (angle == 0) - return new AxisAngle4d(new Vector3d(), 0); Vector3d axis = new Vector3d(); axis.cross(from, to); + if (axis.epsilonEquals(new Vector3d(), 1E-8)) + return new AxisAngle4d(new Vector3d(1,0,0), 0); axis.normalize(); return new AxisAngle4d(axis, angle); } public static float[] matrix4dToFloatArray(Matrix4d m) { return new float[] { (float) m.m00, (float) m.m01, (float) m.m02, (float) m.m03, (float) m.m10, (float) m.m11, (float) m.m12, (float) m.m13, (float) m.m20, (float) m.m21, (float) m.m22, (float) m.m23, (float) m.m30, (float) m.m31, (float) m.m32, (float) m.m33 }; } }
false
true
public static AxisAngle4d rotateFromTo(Vector3d from, Vector3d to) { double angle = from.angle(to); if (angle == 0) return new AxisAngle4d(new Vector3d(), 0); Vector3d axis = new Vector3d(); axis.cross(from, to); axis.normalize(); return new AxisAngle4d(axis, angle); }
public static AxisAngle4d rotateFromTo(Vector3d from, Vector3d to) { double angle = from.angle(to); Vector3d axis = new Vector3d(); axis.cross(from, to); if (axis.epsilonEquals(new Vector3d(), 1E-8)) return new AxisAngle4d(new Vector3d(1,0,0), 0); axis.normalize(); return new AxisAngle4d(axis, angle); }
diff --git a/core/src/main/java/me/prettyprint/cassandra/service/template/SuperCfResultWrapper.java b/core/src/main/java/me/prettyprint/cassandra/service/template/SuperCfResultWrapper.java index b3699151..921ca47b 100644 --- a/core/src/main/java/me/prettyprint/cassandra/service/template/SuperCfResultWrapper.java +++ b/core/src/main/java/me/prettyprint/cassandra/service/template/SuperCfResultWrapper.java @@ -1,219 +1,219 @@ package me.prettyprint.cassandra.service.template; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.UUID; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.HColumnImpl; import me.prettyprint.cassandra.model.HSuperColumnImpl; import me.prettyprint.cassandra.serializers.BooleanSerializer; import me.prettyprint.cassandra.serializers.ByteBufferSerializer; import me.prettyprint.cassandra.serializers.BytesArraySerializer; import me.prettyprint.cassandra.serializers.DateSerializer; import me.prettyprint.cassandra.serializers.IntegerSerializer; import me.prettyprint.cassandra.serializers.LongSerializer; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.cassandra.serializers.UUIDSerializer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.factory.HFactory; import org.apache.cassandra.thrift.Column; import org.apache.cassandra.thrift.ColumnOrSuperColumn; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides access to the current row of data during super column queries. * * @author zznate * @param <N> the super column's sub column name type */ public class SuperCfResultWrapper<K,SN,N> extends AbstractResultWrapper<K,N> implements SuperCfResult<K,SN,N> { private static final Logger log = LoggerFactory.getLogger(SuperCfResultWrapper.class); private Map<SN,Map<N,HColumn<N,ByteBuffer>>> columns = new LinkedHashMap<SN,Map<N,HColumn<N,ByteBuffer>>>(); private Iterator<Map.Entry<ByteBuffer, List<ColumnOrSuperColumn>>> rows; private Map.Entry<ByteBuffer, List<ColumnOrSuperColumn>> entry; private ExecutionResult<Map<ByteBuffer,List<ColumnOrSuperColumn>>> executionResult; private List<SN> superColumns; private Map<N,HColumn<N,ByteBuffer>> subColumns = new LinkedHashMap<N,HColumn<N,ByteBuffer>>(); private SN currentSuperColumn; private boolean hasEntries; private Serializer<SN> sNameSerializer; public SuperCfResultWrapper(Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> subSerializer, ExecutionResult<Map<ByteBuffer, List<ColumnOrSuperColumn>>> executionResult) { super(keySerializer, subSerializer, executionResult); this.sNameSerializer = sNameSerializer; this.rows = executionResult.get().entrySet().iterator(); next(); hasEntries = getSuperColumns() != null && getSuperColumns().size() > 0; } @Override public SuperCfResult<K, SN, N> next() { if ( !hasNext() ) { throw new NoSuchElementException("No more rows left on this HColumnFamily"); } entry = rows.next(); log.debug("found entry {} with value {}", getKey(), entry.getValue()); applyToRow(entry.getValue()); return this; } private void applyToRow(List<ColumnOrSuperColumn> cosclist) { superColumns = new ArrayList<SN>(cosclist.size()); for (Iterator<ColumnOrSuperColumn> iterator = cosclist.iterator(); iterator.hasNext();) { ColumnOrSuperColumn cosc = iterator.next(); - SN sColName = sNameSerializer.fromByteBuffer(cosc.super_column.name); + SN sColName = sNameSerializer.fromByteBuffer(cosc.super_column.name.duplicate()); log.debug("cosc {}", cosc.super_column); superColumns.add(sColName); Iterator<Column> tcolumns = cosc.getSuper_column().getColumnsIterator(); Map<N,HColumn<N,ByteBuffer>> subColMap = new LinkedHashMap<N, HColumn<N,ByteBuffer>>(); while ( tcolumns.hasNext() ) { Column col = tcolumns.next(); - subColMap.put(columnNameSerializer.fromByteBuffer(col.name), new HColumnImpl<N, ByteBuffer>(col, columnNameSerializer, ByteBufferSerializer.get())); + subColMap.put(columnNameSerializer.fromByteBuffer(col.name.duplicate()), new HColumnImpl<N, ByteBuffer>(col, columnNameSerializer, ByteBufferSerializer.get())); } columns.put(sColName, subColMap); } } public List<SN> getSuperColumns() { return superColumns; } @Override public ByteBuffer getColumnValue(N columnName) { HColumn<N,ByteBuffer> col = getColumn( columnName ); return col != null ? col.getValue() : null; } @Override public K getKey() { return keySerializer.fromByteBuffer(entry.getKey().duplicate()); } @Override public HColumn<N, ByteBuffer> getColumn(N columnName) { return subColumns == null ? null : subColumns.get( columnName ); } @Override public Collection<N> getColumnNames() { return subColumns != null ? subColumns.keySet() : new ArrayList<N>(); } @Override public boolean hasNext() { return rows.hasNext(); } @Override public void remove() { rows.remove(); } private <V> V extractType(SN sColumnName, N columnName, Serializer<V> valueSerializer) { Map<N, HColumn<N, ByteBuffer>> map = columns.get(sColumnName); if ( map != null && map.get(columnName) != null ) return valueSerializer.fromByteBuffer(map.get(columnName).getValue()); return null; } @Override public Boolean getBoolean(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, BooleanSerializer.get()); } @Override public byte[] getByteArray(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, BytesArraySerializer.get()); } @Override public Date getDate(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, DateSerializer.get()); } @Override public Integer getInteger(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, IntegerSerializer.get()); } @Override public Long getLong(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, LongSerializer.get()); } @Override public String getString(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, StringSerializer.get()); } @Override public UUID getUUID(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, UUIDSerializer.get()); } @Override public ByteBuffer getByteBuffer(SN sColumnName, N columnName) { return extractType(sColumnName, columnName, ByteBufferSerializer.get()); } @Override public SN getActiveSuperColumn() { return currentSuperColumn; } @Override public HSuperColumn<SN, N, ByteBuffer> getSuperColumn(SN sColumnName) { Map<N, HColumn<N, ByteBuffer>> subCols = columns.get(sColumnName); HSuperColumnImpl<SN, N, ByteBuffer> scol = new HSuperColumnImpl<SN, N, ByteBuffer>(sColumnName, new ArrayList<HColumn<N,ByteBuffer>>(subCols.values()), HFactory.createClock(), sNameSerializer, columnNameSerializer, ByteBufferSerializer.get()); return scol; } @Override public void applySuperColumn(SN sColumnName) { this.currentSuperColumn = sColumnName; this.subColumns = columns.get(currentSuperColumn); } @Override public boolean hasResults() { return hasEntries; } }
false
true
private void applyToRow(List<ColumnOrSuperColumn> cosclist) { superColumns = new ArrayList<SN>(cosclist.size()); for (Iterator<ColumnOrSuperColumn> iterator = cosclist.iterator(); iterator.hasNext();) { ColumnOrSuperColumn cosc = iterator.next(); SN sColName = sNameSerializer.fromByteBuffer(cosc.super_column.name); log.debug("cosc {}", cosc.super_column); superColumns.add(sColName); Iterator<Column> tcolumns = cosc.getSuper_column().getColumnsIterator(); Map<N,HColumn<N,ByteBuffer>> subColMap = new LinkedHashMap<N, HColumn<N,ByteBuffer>>(); while ( tcolumns.hasNext() ) { Column col = tcolumns.next(); subColMap.put(columnNameSerializer.fromByteBuffer(col.name), new HColumnImpl<N, ByteBuffer>(col, columnNameSerializer, ByteBufferSerializer.get())); } columns.put(sColName, subColMap); } }
private void applyToRow(List<ColumnOrSuperColumn> cosclist) { superColumns = new ArrayList<SN>(cosclist.size()); for (Iterator<ColumnOrSuperColumn> iterator = cosclist.iterator(); iterator.hasNext();) { ColumnOrSuperColumn cosc = iterator.next(); SN sColName = sNameSerializer.fromByteBuffer(cosc.super_column.name.duplicate()); log.debug("cosc {}", cosc.super_column); superColumns.add(sColName); Iterator<Column> tcolumns = cosc.getSuper_column().getColumnsIterator(); Map<N,HColumn<N,ByteBuffer>> subColMap = new LinkedHashMap<N, HColumn<N,ByteBuffer>>(); while ( tcolumns.hasNext() ) { Column col = tcolumns.next(); subColMap.put(columnNameSerializer.fromByteBuffer(col.name.duplicate()), new HColumnImpl<N, ByteBuffer>(col, columnNameSerializer, ByteBufferSerializer.get())); } columns.put(sColName, subColMap); } }
diff --git a/src/net/sf/freecol/common/networking/DeclareIndependenceMessage.java b/src/net/sf/freecol/common/networking/DeclareIndependenceMessage.java index 62da00a85..e89db08c2 100644 --- a/src/net/sf/freecol/common/networking/DeclareIndependenceMessage.java +++ b/src/net/sf/freecol/common/networking/DeclareIndependenceMessage.java @@ -1,154 +1,162 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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 2 of the License, or * (at your option) any later version. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import net.sf.freecol.common.model.FreeColObject; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Player.PlayerType; import net.sf.freecol.common.model.Player.Stance; import net.sf.freecol.common.model.Unit; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.model.ServerPlayer; /** * The message sent when a player declares independence. */ public class DeclareIndependenceMessage extends Message { /** * The new name for the rebelling nation */ private String nationName; /** * The new name for the rebelling country */ private String countryName; /** * Create a new <code>DeclareIndependenceMessage</code> with the * supplied name. * * @param nationName The new name for the rebelling nation. * @param countryName The new name for the rebelling country. */ public DeclareIndependenceMessage(String nationName, String countryName) { this.nationName = nationName; this.countryName = countryName; } /** * Create a new <code>DeclareIndependenceMessage</code> from a * supplied element. * * @param game The <code>Game</code> this message belongs to. * @param element The <code>Element</code> to use to create the message. */ public DeclareIndependenceMessage(Game game, Element element) { this.nationName = element.getAttribute("nationName"); this.countryName = element.getAttribute("countryName"); } /** * Handle a "declareIndependence"-message. * * @param server The <code>FreeColServer</code> handling the message. * @param player The <code>Player</code> the message applies to. * @param connection The <code>Connection</code> the message is from. * * @return An update <code>Element</code> describing the REF and the * rebel player, or an error <code>Element</code> on failure. */ public Element handle(FreeColServer server, Player player, Connection connection) { if (nationName == null || nationName.length() == 0 || countryName == null || countryName.length() == 0) { return Message.clientError("Empty nation or country name."); } if (player.getSoL() < 50) { return Message.clientError("Cannot declare independence with SoL < 50: " + player.getSoL()); } if (player.getPlayerType() != PlayerType.COLONIAL) { return Message.clientError("Only colonial players can declare independence."); } // Create and arm the REF player ServerPlayer serverPlayer = server.getPlayer(connection); ServerPlayer refPlayer = server.getInGameController().createREFPlayer(serverPlayer); server.getInGameController().createREFUnits(serverPlayer, refPlayer); // Liberty or else List<FreeColObject> changes = serverPlayer.declareIndependence(nationName, countryName); // Tell the other players about the new names and rebel status Element reply = Message.createNewRootElement("update"); Document doc = reply.getOwnerDocument(); reply.appendChild(player.toXMLElementPartial(doc, "playerType", "independentNationName", "newLandName")); server.getServer().sendToAll(reply, connection); // Do this after the above update, so the other players see // the new nation name declaring war. serverPlayer.changeRelationWithPlayer(refPlayer, Stance.WAR); // Update the player reply = Message.createNewRootElement("multiple"); doc = reply.getOwnerDocument(); Element update = doc.createElement("update"); + Element remove = doc.createElement("remove"); Element messages = doc.createElement("addMessages"); reply.appendChild(update); - reply.appendChild(messages); for (FreeColObject obj : changes) { if (obj instanceof ModelMessage) { messages.appendChild(obj.toXMLElement(player, doc)); + } else if (obj instanceof Unit && ((Unit) obj).isDisposed()) { + ((Unit) obj).addToRemoveElement(remove); } else { update.appendChild(obj.toXMLElement(player, doc)); } } + if (remove.hasChildNodes()) { + reply.appendChild(remove); + } + if (messages.hasChildNodes()) { + reply.appendChild(messages); + } return reply; } /** * Convert this DeclareIndependenceMessage to XML. * * @return The XML representation of this message. */ public Element toXMLElement() { Element result = createNewRootElement(getXMLElementTagName()); result.setAttribute("nationName", nationName); result.setAttribute("countryName", countryName); return result; } /** * The tag name of the root element representing this object. * * @return "declareIndependence". */ public static String getXMLElementTagName() { return "declareIndependence"; } }
false
true
public Element handle(FreeColServer server, Player player, Connection connection) { if (nationName == null || nationName.length() == 0 || countryName == null || countryName.length() == 0) { return Message.clientError("Empty nation or country name."); } if (player.getSoL() < 50) { return Message.clientError("Cannot declare independence with SoL < 50: " + player.getSoL()); } if (player.getPlayerType() != PlayerType.COLONIAL) { return Message.clientError("Only colonial players can declare independence."); } // Create and arm the REF player ServerPlayer serverPlayer = server.getPlayer(connection); ServerPlayer refPlayer = server.getInGameController().createREFPlayer(serverPlayer); server.getInGameController().createREFUnits(serverPlayer, refPlayer); // Liberty or else List<FreeColObject> changes = serverPlayer.declareIndependence(nationName, countryName); // Tell the other players about the new names and rebel status Element reply = Message.createNewRootElement("update"); Document doc = reply.getOwnerDocument(); reply.appendChild(player.toXMLElementPartial(doc, "playerType", "independentNationName", "newLandName")); server.getServer().sendToAll(reply, connection); // Do this after the above update, so the other players see // the new nation name declaring war. serverPlayer.changeRelationWithPlayer(refPlayer, Stance.WAR); // Update the player reply = Message.createNewRootElement("multiple"); doc = reply.getOwnerDocument(); Element update = doc.createElement("update"); Element messages = doc.createElement("addMessages"); reply.appendChild(update); reply.appendChild(messages); for (FreeColObject obj : changes) { if (obj instanceof ModelMessage) { messages.appendChild(obj.toXMLElement(player, doc)); } else { update.appendChild(obj.toXMLElement(player, doc)); } } return reply; }
public Element handle(FreeColServer server, Player player, Connection connection) { if (nationName == null || nationName.length() == 0 || countryName == null || countryName.length() == 0) { return Message.clientError("Empty nation or country name."); } if (player.getSoL() < 50) { return Message.clientError("Cannot declare independence with SoL < 50: " + player.getSoL()); } if (player.getPlayerType() != PlayerType.COLONIAL) { return Message.clientError("Only colonial players can declare independence."); } // Create and arm the REF player ServerPlayer serverPlayer = server.getPlayer(connection); ServerPlayer refPlayer = server.getInGameController().createREFPlayer(serverPlayer); server.getInGameController().createREFUnits(serverPlayer, refPlayer); // Liberty or else List<FreeColObject> changes = serverPlayer.declareIndependence(nationName, countryName); // Tell the other players about the new names and rebel status Element reply = Message.createNewRootElement("update"); Document doc = reply.getOwnerDocument(); reply.appendChild(player.toXMLElementPartial(doc, "playerType", "independentNationName", "newLandName")); server.getServer().sendToAll(reply, connection); // Do this after the above update, so the other players see // the new nation name declaring war. serverPlayer.changeRelationWithPlayer(refPlayer, Stance.WAR); // Update the player reply = Message.createNewRootElement("multiple"); doc = reply.getOwnerDocument(); Element update = doc.createElement("update"); Element remove = doc.createElement("remove"); Element messages = doc.createElement("addMessages"); reply.appendChild(update); for (FreeColObject obj : changes) { if (obj instanceof ModelMessage) { messages.appendChild(obj.toXMLElement(player, doc)); } else if (obj instanceof Unit && ((Unit) obj).isDisposed()) { ((Unit) obj).addToRemoveElement(remove); } else { update.appendChild(obj.toXMLElement(player, doc)); } } if (remove.hasChildNodes()) { reply.appendChild(remove); } if (messages.hasChildNodes()) { reply.appendChild(messages); } return reply; }
diff --git a/src/net/epsilony/tsmf/util/ui/PhysicalModelTransform.java b/src/net/epsilony/tsmf/util/ui/PhysicalModelTransform.java index ac13bbd..050618e 100644 --- a/src/net/epsilony/tsmf/util/ui/PhysicalModelTransform.java +++ b/src/net/epsilony/tsmf/util/ui/PhysicalModelTransform.java @@ -1,52 +1,52 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.epsilony.tsmf.util.ui; import java.awt.geom.AffineTransform; /** * * @author epsilon */ public class PhysicalModelTransform extends AffineTransform { public static final double SCALE_LOWER_LIMITE = 1e-15; private int defaultX; private int defaultY; private double defaultScale; public void unitScaleAndSetOrigin(int originX, int originY) { setToIdentity(); translate(originX, originY); scale(1, -1); } void translateOrigin(int dx, int dy) { preConcatenate(AffineTransform.getTranslateInstance(dx, dy)); } public void scaleByCenter(int centerX, int centerY, double scale) { AffineTransform tranformBack = new AffineTransform(this); - setToTranslation(centerX, centerX); + setToTranslation(centerX, centerY); scale(scale, scale); - translate(-centerX, -centerX); + translate(-centerX, -centerY); if (Math.abs(getScaleX()) < SCALE_LOWER_LIMITE || Math.abs(getScaleY()) < SCALE_LOWER_LIMITE) { setTransform(tranformBack); } else { concatenate(tranformBack); } } public void setDefault(int centerX, int centerY, double scale) { defaultX = centerX; defaultY = centerY; defaultScale = scale; } public void resetToDefault() { unitScaleAndSetOrigin(defaultX, defaultY); scaleByCenter(0, 0, defaultScale); } }
false
true
public void scaleByCenter(int centerX, int centerY, double scale) { AffineTransform tranformBack = new AffineTransform(this); setToTranslation(centerX, centerX); scale(scale, scale); translate(-centerX, -centerX); if (Math.abs(getScaleX()) < SCALE_LOWER_LIMITE || Math.abs(getScaleY()) < SCALE_LOWER_LIMITE) { setTransform(tranformBack); } else { concatenate(tranformBack); } }
public void scaleByCenter(int centerX, int centerY, double scale) { AffineTransform tranformBack = new AffineTransform(this); setToTranslation(centerX, centerY); scale(scale, scale); translate(-centerX, -centerY); if (Math.abs(getScaleX()) < SCALE_LOWER_LIMITE || Math.abs(getScaleY()) < SCALE_LOWER_LIMITE) { setTransform(tranformBack); } else { concatenate(tranformBack); } }
diff --git a/test/sandbox/com/sun/tools/javafx/api/JFXC3382.java b/test/sandbox/com/sun/tools/javafx/api/JFXC3382.java index 5f4b71ad4..b557326ca 100644 --- a/test/sandbox/com/sun/tools/javafx/api/JFXC3382.java +++ b/test/sandbox/com/sun/tools/javafx/api/JFXC3382.java @@ -1,134 +1,134 @@ /* * Copyright 2007-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.api; import com.sun.javafx.api.JavafxcTask; import com.sun.javafx.api.tree.FunctionDefinitionTree; import com.sun.javafx.api.tree.FunctionInvocationTree; import com.sun.javafx.api.tree.JavaFXTreePathScanner; import com.sun.javafx.api.tree.UnitTree; import com.sun.tools.javac.util.JavacFileManager; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.tools.JavaFileObject; import org.junit.Test; import org.junit.Before; import org.junit.After; import static org.junit.Assert.*; /** * This test makes sure that the AllTrees.fx file contains all tree constructs * from com.sun.javafx.api.tree.Tree.JavaFXKind.values(). * * @author David Strupl */ public class JFXC3382 { private static final String SEP = File.pathSeparator; private static final String DIR = File.separator; private String javafxLibs = "dist/lib/shared"; private String javafxDeskLibs = "dist/lib/desktop"; private String inputDir = "test/sandbox/com/sun/tools/javafx/api"; private JavafxcTrees trees; private UnitTree ut; @Before public void setup() throws IOException { JavafxcTool tool = JavafxcTool.create (); JavacFileManager manager = tool.getStandardFileManager (null, null, Charset.defaultCharset ()); ArrayList<JavaFileObject> filesToCompile = new ArrayList<JavaFileObject> (); - filesToCompile.add (manager.getFileForInput (inputDir + DIR + "FunctionParametersTest.fx")); + filesToCompile.add (manager.getFileForInput (inputDir + DIR + "JFXC3382.fx")); JavafxcTask task = tool.getTask (null, null, null, Arrays.asList ("-XDdisableStringFolding", "-cp", javafxLibs + DIR + "javafxc.jar" + SEP + javafxLibs + DIR + "javafxrt.jar" + SEP + javafxDeskLibs + DIR + "javafx-ui-common.jar" + SEP + inputDir ), filesToCompile); task.parse(); Iterable analyzeUnits = task.analyze(); trees = JavafxcTrees.instance(task); ut = (UnitTree)analyzeUnits.iterator().next(); } @After public void teardown() { trees = null; ut = null; } @Test public void testFunctionInvocationParameters() throws Exception { JavaFXTreePathScanner<Void, Void> scanner = new JavaFXTreePathScanner<Void, Void>() { @Override public Void visitMethodInvocation(FunctionInvocationTree node, Void p) { Element e = trees.getElement(getCurrentPath()); System.out.println(node); assertEquals(1, ((ExecutableElement)e).getTypeParameters().size()); return super.visitMethodInvocation(node, p); } }; scanner.scan(ut, null); } @Test public void testFunctionDefinitionParameters() throws Exception { JavaFXTreePathScanner<Void, Void> scanner = new JavaFXTreePathScanner<Void, Void>() { @Override public Void visitFunctionDefinition(FunctionDefinitionTree node, Void p) { Element e = trees.getElement(getCurrentPath()); System.out.println(node); assertEquals(1, ((ExecutableElement)e).getTypeParameters().size()); return super.visitFunctionDefinition(node, p); } }; scanner.scan(ut, null); } private static File getTmpDir() { try { File f = File.createTempFile("dummy", "file"); f.deleteOnExit(); File tmpdir = f.getParentFile(); if (tmpdir != null) return tmpdir; } catch (IOException ex) { } File f = new File("test-output"); f.mkdir(); return f; } }
true
true
public void setup() throws IOException { JavafxcTool tool = JavafxcTool.create (); JavacFileManager manager = tool.getStandardFileManager (null, null, Charset.defaultCharset ()); ArrayList<JavaFileObject> filesToCompile = new ArrayList<JavaFileObject> (); filesToCompile.add (manager.getFileForInput (inputDir + DIR + "FunctionParametersTest.fx")); JavafxcTask task = tool.getTask (null, null, null, Arrays.asList ("-XDdisableStringFolding", "-cp", javafxLibs + DIR + "javafxc.jar" + SEP + javafxLibs + DIR + "javafxrt.jar" + SEP + javafxDeskLibs + DIR + "javafx-ui-common.jar" + SEP + inputDir ), filesToCompile); task.parse(); Iterable analyzeUnits = task.analyze(); trees = JavafxcTrees.instance(task); ut = (UnitTree)analyzeUnits.iterator().next(); }
public void setup() throws IOException { JavafxcTool tool = JavafxcTool.create (); JavacFileManager manager = tool.getStandardFileManager (null, null, Charset.defaultCharset ()); ArrayList<JavaFileObject> filesToCompile = new ArrayList<JavaFileObject> (); filesToCompile.add (manager.getFileForInput (inputDir + DIR + "JFXC3382.fx")); JavafxcTask task = tool.getTask (null, null, null, Arrays.asList ("-XDdisableStringFolding", "-cp", javafxLibs + DIR + "javafxc.jar" + SEP + javafxLibs + DIR + "javafxrt.jar" + SEP + javafxDeskLibs + DIR + "javafx-ui-common.jar" + SEP + inputDir ), filesToCompile); task.parse(); Iterable analyzeUnits = task.analyze(); trees = JavafxcTrees.instance(task); ut = (UnitTree)analyzeUnits.iterator().next(); }
diff --git a/src/main/java/de/holidayinsider/skimmy/SkimmyTest.java b/src/main/java/de/holidayinsider/skimmy/SkimmyTest.java index 0b7028f..5bf8b59 100644 --- a/src/main/java/de/holidayinsider/skimmy/SkimmyTest.java +++ b/src/main/java/de/holidayinsider/skimmy/SkimmyTest.java @@ -1,322 +1,323 @@ package de.holidayinsider.skimmy; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; /** * User: martinstolz * Date: 03.07.12 */ public class SkimmyTest { private Properties uriList = new Properties(); private Properties hosts = new Properties(); private String suiteName; private String targetServer; public SkimmyTest(String suiteName, String host) { this.suiteName = suiteName; try { uriList.load(new FileInputStream(new File("suites/" + suiteName + "/urilist.properties"))); hosts.load(new FileInputStream(new File("suites/" + suiteName + "/hosts.properties"))); } catch (IOException e) { throw new RuntimeException(e); } this.targetServer = hosts.getProperty(host); if (targetServer == null) { throw new IllegalArgumentException("domain not found! " + host); } } /** * Runs the tests. */ public void runTests() { File wantedDir = new File("suites/" + suiteName + "/wanted"); if (!wantedDir.exists()) { wantedDir.mkdirs(); } // check wanted pictures exist for all uris for (Object keyObj : uriList.keySet()) { String key = (String) keyObj; String uri = buildUri(uriList.getProperty(key)); String wantedFile = "suites/" + suiteName + "/wanted/" + key + ".png"; File wanted = new File(wantedFile); // get initial images for those urls and put them in wanted. if (!wanted.exists()) { generateImage(key, uri, "suites/" + suiteName + "/wanted"); } } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String runTargetDir = "suites/" + suiteName + "/runs/" + format.format(new Date()); SkimmyReport report = new SkimmyReport(); report.setSuiteName(suiteName); report.setHostName(targetServer); new File(runTargetDir).mkdirs(); // for all uris List failed = new ArrayList<String>(); for (Object keyObj : uriList.keySet()) { String key = (String) keyObj; String url = buildUri(uriList.getProperty(key)); SkimmyReportItem item = new SkimmyReportItem(); item.setKey(key); item.setTimestamp(System.currentTimeMillis()); item.setUrl(url); report.getItems().add(item); // load wanted image String wantedImgFile = "suites/" + suiteName + "/wanted/" + key + ".png"; BufferedImage wantedImg = loadImage(wantedImgFile); // relative path of report.html to the wanted images... item.setWantedImgPath("../../wanted/" + key + ".png"); // load live image into suite run dir generateImage(key, url, runTargetDir); BufferedImage currentImg = loadImage(runTargetDir + "/" + key + ".png"); item.setCurrentImgPath(key + ".png"); int width = Math.min(wantedImg.getWidth(), currentImg.getWidth()); int height = Math.min(wantedImg.getHeight(), currentImg.getHeight()); boolean failure = false; int totalPixel = 0; int failedPixel = 0; // if the width differs more than 30% its failed in any case. if (Math.abs(width - wantedImg.getWidth()) / width > 0.1 || Math.abs(height - wantedImg.getHeight()) / height > 0.1) { failure = true; + totalPixel = 1; } else { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int wantedRGB = wantedImg.getRGB(x, y); int currentRGB = 1; if (currentImg.getHeight() > y && currentImg.getWidth() > x) { currentRGB = currentImg.getRGB(x, y); } // if its pitch black or blacked out we dont want to compare it. if (wantedRGB == 0xFF000000) { continue; } if (wantedRGB != currentRGB) { failure = true; failedPixel ++; currentImg.setRGB(x, y, 0xFFFF0000); } totalPixel ++; } } if (failure) { failure = false; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = currentImg.getRGB(x, y); if (rgb == 0xFFFF0000) { failure = failure || checkAreaForFail(x, y, currentImg); } if (failure) { break; } } } } } if (failure) { File failImage = new File(runTargetDir + "/failed"); failImage.mkdirs(); failImage = new File(failImage, key + ".png"); item.setFailed(true); item.setFailedImgPath("failed/" + key + ".png"); // make all non-failed areas very much lighter to make the error stand out... for (int x = 0; x < currentImg.getWidth(); x++) { for (int y = 0; y < currentImg.getHeight(); y++) { int rgb = currentImg.getRGB(x, y); if (rgb != 0xFFFF0000) { // make shadow of the page content so you see the errors better. Color c = new Color(rgb); c = c.brighter(); // dont make it too bright if (c.getRGB() != 0xFFFFFFFF) { c = c.brighter(); } rgb = c.getRGB(); currentImg.setRGB(x, y, rgb); } } } try { ImageIO.write(currentImg, "png", failImage); } catch (IOException io) { throw new RuntimeException(io); } StringBuilder build = new StringBuilder(); build.append("FAIL " + url + "\n"); build.append(" -> " + ((failedPixel / totalPixel) * 100) + " percent"); build.append(" -> saved to " + failImage.getPath()); failed.add(build.toString()); } } // generate report and fin. try { generateReport(report, runTargetDir); } catch (Exception e) { throw new RuntimeException(e); } } public void generateReport(Object model, String targetDir) throws Exception { Configuration cfg = new Configuration(); ////cfg.setDirectoryForTemplateLoading( //// new File("/where/you/store/templates")); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setTemplateLoader(new FlexibleTemplateLoader()); Template tpl = cfg.getTemplate("results.ftl"); tpl.process(model, new FileWriter(targetDir + "/report.html")); } /** * Checks all surrounding pixels for a failure. * Only if a certain percentage is "red" we decide its really a failure * to account for anti-aliasing differences which generate false positives. * * @param xPoint * @param yPoint * @param image * @return */ private boolean checkAreaForFail(int xPoint, int yPoint, BufferedImage image) { int failCount = 0; int startX = xPoint - 1; int startY = yPoint - 1; int endX = xPoint + 1; int endY = yPoint + 1; if (startX < 0) startX = 0; if (endX > image.getWidth() - 1) endX = image.getWidth() -1; if (startY < 0) startY = 0; if (endY > image.getWidth() - 1) endX = image.getWidth() -1; for (int x = startX; x <= endX; x++) { for (int y = startY; y <= endY; y++) { int rgb = image.getRGB(x, y); if (rgb == 0xFFFF0000) { failCount ++; } } } return failCount > 7; } /** * Does neccessary replacements in the uri to account for dates etc. * @param uri * @return */ private String buildUri(String uri) { uri = uri.replace("{DOMAIN}", targetServer); return uri; } /** * Well, it loads an image. * @param file * @return */ private BufferedImage loadImage(String file) { try { BufferedImage in = ImageIO.read(new File(file)); return in; } catch (Exception e) { throw new RuntimeException(e); } } /** * Calls webkit2png to generate a image from the given url to be saved in targetDir * with the given tag. * * @param tag * @param url * @param targetDir * @return */ private boolean generateImage(String tag, String url, String targetDir) { StringBuilder cmd = new StringBuilder(); cmd.append("python src/main/resources/webkit2png.py -F -W 1280 -H 1024 --delay 10 "); cmd.append("-o current"); cmd.append(" "); cmd.append(url); System.out.println("Fetching image: " + url); execute(cmd.toString()); execute("mv current-full.png " + targetDir + "/" + tag + ".png"); return true; } /** * A wrapper function for executing shell commands. * * @param command */ private void execute(String command) { try { System.out.println("=> Execute " + command); Process process = Runtime.getRuntime().exec(command); int c; InputStream in = process.getInputStream(); while ((c = in.read()) != -1) { System.out.print((char) c); } in.close(); System.out.println("=> Execute finished"); process.waitFor(); if (process.exitValue() != 0) { throw new RuntimeException("execute failed " + command + " with " + process.exitValue()); } } catch (Exception e) { throw new RuntimeException("execute failed " + command + " with exception", e); } } }
true
true
public void runTests() { File wantedDir = new File("suites/" + suiteName + "/wanted"); if (!wantedDir.exists()) { wantedDir.mkdirs(); } // check wanted pictures exist for all uris for (Object keyObj : uriList.keySet()) { String key = (String) keyObj; String uri = buildUri(uriList.getProperty(key)); String wantedFile = "suites/" + suiteName + "/wanted/" + key + ".png"; File wanted = new File(wantedFile); // get initial images for those urls and put them in wanted. if (!wanted.exists()) { generateImage(key, uri, "suites/" + suiteName + "/wanted"); } } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String runTargetDir = "suites/" + suiteName + "/runs/" + format.format(new Date()); SkimmyReport report = new SkimmyReport(); report.setSuiteName(suiteName); report.setHostName(targetServer); new File(runTargetDir).mkdirs(); // for all uris List failed = new ArrayList<String>(); for (Object keyObj : uriList.keySet()) { String key = (String) keyObj; String url = buildUri(uriList.getProperty(key)); SkimmyReportItem item = new SkimmyReportItem(); item.setKey(key); item.setTimestamp(System.currentTimeMillis()); item.setUrl(url); report.getItems().add(item); // load wanted image String wantedImgFile = "suites/" + suiteName + "/wanted/" + key + ".png"; BufferedImage wantedImg = loadImage(wantedImgFile); // relative path of report.html to the wanted images... item.setWantedImgPath("../../wanted/" + key + ".png"); // load live image into suite run dir generateImage(key, url, runTargetDir); BufferedImage currentImg = loadImage(runTargetDir + "/" + key + ".png"); item.setCurrentImgPath(key + ".png"); int width = Math.min(wantedImg.getWidth(), currentImg.getWidth()); int height = Math.min(wantedImg.getHeight(), currentImg.getHeight()); boolean failure = false; int totalPixel = 0; int failedPixel = 0; // if the width differs more than 30% its failed in any case. if (Math.abs(width - wantedImg.getWidth()) / width > 0.1 || Math.abs(height - wantedImg.getHeight()) / height > 0.1) { failure = true; } else { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int wantedRGB = wantedImg.getRGB(x, y); int currentRGB = 1; if (currentImg.getHeight() > y && currentImg.getWidth() > x) { currentRGB = currentImg.getRGB(x, y); } // if its pitch black or blacked out we dont want to compare it. if (wantedRGB == 0xFF000000) { continue; } if (wantedRGB != currentRGB) { failure = true; failedPixel ++; currentImg.setRGB(x, y, 0xFFFF0000); } totalPixel ++; } } if (failure) { failure = false; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = currentImg.getRGB(x, y); if (rgb == 0xFFFF0000) { failure = failure || checkAreaForFail(x, y, currentImg); } if (failure) { break; } } } } } if (failure) { File failImage = new File(runTargetDir + "/failed"); failImage.mkdirs(); failImage = new File(failImage, key + ".png"); item.setFailed(true); item.setFailedImgPath("failed/" + key + ".png"); // make all non-failed areas very much lighter to make the error stand out... for (int x = 0; x < currentImg.getWidth(); x++) { for (int y = 0; y < currentImg.getHeight(); y++) { int rgb = currentImg.getRGB(x, y); if (rgb != 0xFFFF0000) { // make shadow of the page content so you see the errors better. Color c = new Color(rgb); c = c.brighter(); // dont make it too bright if (c.getRGB() != 0xFFFFFFFF) { c = c.brighter(); } rgb = c.getRGB(); currentImg.setRGB(x, y, rgb); } } } try { ImageIO.write(currentImg, "png", failImage); } catch (IOException io) { throw new RuntimeException(io); } StringBuilder build = new StringBuilder(); build.append("FAIL " + url + "\n"); build.append(" -> " + ((failedPixel / totalPixel) * 100) + " percent"); build.append(" -> saved to " + failImage.getPath()); failed.add(build.toString()); } } // generate report and fin. try { generateReport(report, runTargetDir); } catch (Exception e) { throw new RuntimeException(e); } }
public void runTests() { File wantedDir = new File("suites/" + suiteName + "/wanted"); if (!wantedDir.exists()) { wantedDir.mkdirs(); } // check wanted pictures exist for all uris for (Object keyObj : uriList.keySet()) { String key = (String) keyObj; String uri = buildUri(uriList.getProperty(key)); String wantedFile = "suites/" + suiteName + "/wanted/" + key + ".png"; File wanted = new File(wantedFile); // get initial images for those urls and put them in wanted. if (!wanted.exists()) { generateImage(key, uri, "suites/" + suiteName + "/wanted"); } } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String runTargetDir = "suites/" + suiteName + "/runs/" + format.format(new Date()); SkimmyReport report = new SkimmyReport(); report.setSuiteName(suiteName); report.setHostName(targetServer); new File(runTargetDir).mkdirs(); // for all uris List failed = new ArrayList<String>(); for (Object keyObj : uriList.keySet()) { String key = (String) keyObj; String url = buildUri(uriList.getProperty(key)); SkimmyReportItem item = new SkimmyReportItem(); item.setKey(key); item.setTimestamp(System.currentTimeMillis()); item.setUrl(url); report.getItems().add(item); // load wanted image String wantedImgFile = "suites/" + suiteName + "/wanted/" + key + ".png"; BufferedImage wantedImg = loadImage(wantedImgFile); // relative path of report.html to the wanted images... item.setWantedImgPath("../../wanted/" + key + ".png"); // load live image into suite run dir generateImage(key, url, runTargetDir); BufferedImage currentImg = loadImage(runTargetDir + "/" + key + ".png"); item.setCurrentImgPath(key + ".png"); int width = Math.min(wantedImg.getWidth(), currentImg.getWidth()); int height = Math.min(wantedImg.getHeight(), currentImg.getHeight()); boolean failure = false; int totalPixel = 0; int failedPixel = 0; // if the width differs more than 30% its failed in any case. if (Math.abs(width - wantedImg.getWidth()) / width > 0.1 || Math.abs(height - wantedImg.getHeight()) / height > 0.1) { failure = true; totalPixel = 1; } else { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int wantedRGB = wantedImg.getRGB(x, y); int currentRGB = 1; if (currentImg.getHeight() > y && currentImg.getWidth() > x) { currentRGB = currentImg.getRGB(x, y); } // if its pitch black or blacked out we dont want to compare it. if (wantedRGB == 0xFF000000) { continue; } if (wantedRGB != currentRGB) { failure = true; failedPixel ++; currentImg.setRGB(x, y, 0xFFFF0000); } totalPixel ++; } } if (failure) { failure = false; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = currentImg.getRGB(x, y); if (rgb == 0xFFFF0000) { failure = failure || checkAreaForFail(x, y, currentImg); } if (failure) { break; } } } } } if (failure) { File failImage = new File(runTargetDir + "/failed"); failImage.mkdirs(); failImage = new File(failImage, key + ".png"); item.setFailed(true); item.setFailedImgPath("failed/" + key + ".png"); // make all non-failed areas very much lighter to make the error stand out... for (int x = 0; x < currentImg.getWidth(); x++) { for (int y = 0; y < currentImg.getHeight(); y++) { int rgb = currentImg.getRGB(x, y); if (rgb != 0xFFFF0000) { // make shadow of the page content so you see the errors better. Color c = new Color(rgb); c = c.brighter(); // dont make it too bright if (c.getRGB() != 0xFFFFFFFF) { c = c.brighter(); } rgb = c.getRGB(); currentImg.setRGB(x, y, rgb); } } } try { ImageIO.write(currentImg, "png", failImage); } catch (IOException io) { throw new RuntimeException(io); } StringBuilder build = new StringBuilder(); build.append("FAIL " + url + "\n"); build.append(" -> " + ((failedPixel / totalPixel) * 100) + " percent"); build.append(" -> saved to " + failImage.getPath()); failed.add(build.toString()); } } // generate report and fin. try { generateReport(report, runTargetDir); } catch (Exception e) { throw new RuntimeException(e); } }
diff --git a/src/main/java/org/jvnet/hudson/plugins/port_allocator/PortAllocator.java b/src/main/java/org/jvnet/hudson/plugins/port_allocator/PortAllocator.java index a8a18f8..0c48b78 100644 --- a/src/main/java/org/jvnet/hudson/plugins/port_allocator/PortAllocator.java +++ b/src/main/java/org/jvnet/hudson/plugins/port_allocator/PortAllocator.java @@ -1,140 +1,140 @@ package org.jvnet.hudson.plugins.port_allocator; import hudson.Launcher; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Executor; import hudson.tasks.BuildWrapper; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import net.sf.json.JSONObject; /** * Allocates TCP Ports on a Computer for consumption and sets it as * envioronet variables, see configuration * * <p> * This just mediates between different Jobs running on the same Computer * by assigning free ports and its the jobs responsibility to open and close the ports. * * <p> * TODO: implement ResourceActivity so that the queue performs intelligent job allocations * based on the port availability, instead of start executing something then block. * * @author Rama Pulavarthi */ public class PortAllocator extends BuildWrapper /* implements ResourceActivity */ { /** * ','-separated list of tokens that designates either port variable names or port numbers. */ public final String portVariables; private PortAllocator(String portVariables){ this.portVariables = portVariables; } private Set<String> getVariables() { StringTokenizer stk = new StringTokenizer(portVariables,","); final Set<String> portVars = new HashSet<String>(); while(stk.hasMoreTokens()) { portVars.add(stk.nextToken().trim()); } return portVars; } public Environment setUp(Build build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); final Set<String> portVars = getVariables(); final Computer cur = Executor.currentExecutor().getOwner(); Map<String,Integer> prefPortMap = new HashMap<String,Integer>(); if (build.getPreviousBuild() != null) { AllocatedPortAction prevAlloc = build.getPreviousBuild().getAction(AllocatedPortAction.class); if (prevAlloc != null) { // try to assign ports assigned in previous build prefPortMap = prevAlloc.getPreviousAllocatedPorts(); } } final PortAllocationManager pam = PortAllocationManager.getManager(cur); final Map<String, Integer> portMap = new HashMap<String, Integer>(); for (String portVar : portVars) { Integer port; try { //check if the users prefers port number port = Integer.parseInt(portVar); logger.println("Allocating TCP port "+port); pam.allocate(build,port); } catch (NumberFormatException ex) { int prefPort = prefPortMap.get(portVar)== null?0:prefPortMap.get(portVar); port = pam.allocateRandom(build,prefPort); logger.println("Allocating TCP port "+portVar+"="+port); } portMap.put(portVar, port); } // TODO: only log messages when we are blocking. logger.println("TCP port allocation complete"); build.addAction(new AllocatedPortAction(portMap)); return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { for (String portVar : portMap.keySet()) { try { //check if port variable is a port number, if so don't set env Integer.parseInt(portVar); } catch (NumberFormatException ex) { env.put(portVar, portMap.get(portVar).toString()); } } } public boolean tearDown(Build build, BuildListener listener) throws IOException, InterruptedException { - for(String portVar: portVars){ - pam.free(portMap.get(portVar)); - portMap.remove(portVar); + for (Integer v : portMap.values()) { + pam.free(v); } + portMap.clear(); return true; } }; } public Descriptor<BuildWrapper> getDescriptor() { return DESCRIPTOR; } public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); public static final class DescriptorImpl extends Descriptor<BuildWrapper> { DescriptorImpl() { super(PortAllocator.class); load(); } public String getDisplayName() { return "Run Port Allocator during build"; } public String getHelpFile() { return "/plugin/port-allocator/help.html"; } @Override public BuildWrapper newInstance(StaplerRequest req, JSONObject formData) throws FormException { return new PortAllocator(req.getParameter("portallocator.portVariables")); } } }
false
true
public Environment setUp(Build build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); final Set<String> portVars = getVariables(); final Computer cur = Executor.currentExecutor().getOwner(); Map<String,Integer> prefPortMap = new HashMap<String,Integer>(); if (build.getPreviousBuild() != null) { AllocatedPortAction prevAlloc = build.getPreviousBuild().getAction(AllocatedPortAction.class); if (prevAlloc != null) { // try to assign ports assigned in previous build prefPortMap = prevAlloc.getPreviousAllocatedPorts(); } } final PortAllocationManager pam = PortAllocationManager.getManager(cur); final Map<String, Integer> portMap = new HashMap<String, Integer>(); for (String portVar : portVars) { Integer port; try { //check if the users prefers port number port = Integer.parseInt(portVar); logger.println("Allocating TCP port "+port); pam.allocate(build,port); } catch (NumberFormatException ex) { int prefPort = prefPortMap.get(portVar)== null?0:prefPortMap.get(portVar); port = pam.allocateRandom(build,prefPort); logger.println("Allocating TCP port "+portVar+"="+port); } portMap.put(portVar, port); } // TODO: only log messages when we are blocking. logger.println("TCP port allocation complete"); build.addAction(new AllocatedPortAction(portMap)); return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { for (String portVar : portMap.keySet()) { try { //check if port variable is a port number, if so don't set env Integer.parseInt(portVar); } catch (NumberFormatException ex) { env.put(portVar, portMap.get(portVar).toString()); } } } public boolean tearDown(Build build, BuildListener listener) throws IOException, InterruptedException { for(String portVar: portVars){ pam.free(portMap.get(portVar)); portMap.remove(portVar); } return true; } }; }
public Environment setUp(Build build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); final Set<String> portVars = getVariables(); final Computer cur = Executor.currentExecutor().getOwner(); Map<String,Integer> prefPortMap = new HashMap<String,Integer>(); if (build.getPreviousBuild() != null) { AllocatedPortAction prevAlloc = build.getPreviousBuild().getAction(AllocatedPortAction.class); if (prevAlloc != null) { // try to assign ports assigned in previous build prefPortMap = prevAlloc.getPreviousAllocatedPorts(); } } final PortAllocationManager pam = PortAllocationManager.getManager(cur); final Map<String, Integer> portMap = new HashMap<String, Integer>(); for (String portVar : portVars) { Integer port; try { //check if the users prefers port number port = Integer.parseInt(portVar); logger.println("Allocating TCP port "+port); pam.allocate(build,port); } catch (NumberFormatException ex) { int prefPort = prefPortMap.get(portVar)== null?0:prefPortMap.get(portVar); port = pam.allocateRandom(build,prefPort); logger.println("Allocating TCP port "+portVar+"="+port); } portMap.put(portVar, port); } // TODO: only log messages when we are blocking. logger.println("TCP port allocation complete"); build.addAction(new AllocatedPortAction(portMap)); return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { for (String portVar : portMap.keySet()) { try { //check if port variable is a port number, if so don't set env Integer.parseInt(portVar); } catch (NumberFormatException ex) { env.put(portVar, portMap.get(portVar).toString()); } } } public boolean tearDown(Build build, BuildListener listener) throws IOException, InterruptedException { for (Integer v : portMap.values()) { pam.free(v); } portMap.clear(); return true; } }; }
diff --git a/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/common/resource/BuildHL7ResourceAction.java b/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/common/resource/BuildHL7ResourceAction.java index 1cd23fe16..764309ade 100755 --- a/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/common/resource/BuildHL7ResourceAction.java +++ b/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/common/resource/BuildHL7ResourceAction.java @@ -1,216 +1,213 @@ package gov.nih.nci.caadapter.ui.common.resource; import gov.nih.nci.caadapter.hl7.mif.v1.BuildResourceUtil; import gov.nih.nci.caadapter.ui.common.AbstractMainFrame; import gov.nih.nci.caadapter.ui.common.DefaultSettings; import gov.nih.nci.caadapter.ui.common.actions.AbstractContextAction; import gov.nih.nci.caadapter.ui.main.HL7AuthorizationDialog; import gov.nih.nci.caadapter.ui.mapping.V2V3.V2MetaCollectorDialog; import gov.nih.nci.caadapter.ui.mapping.V2V3.V2MetaBasicInstallDialog; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class BuildHL7ResourceAction extends AbstractContextAction { /** * */ private static final long serialVersionUID = 1L; public static final String COMMAND_BUILD_V3 = "Load HL7 v3 Normative Edition Processable Artifacts"; public static final String COMMAND_BUILD_V2 = "Load HL7 v2 Processable Artifacts"; public static final String COMMAND_BUILD_V2_CORE ="Load HL7 v2 Core Artifacts"; public static final String COMMAND_BUILD_V_MESSAGE = "Load HL7 v2 Message Artifacts"; private AbstractMainFrame mainFrame; private static final String RESOURCE_NAME_V3="resource.zip"; private static final String RESOURCE_NAME_V2="resourceV2.zip"; /** * Defines an <code>Action</code> object with the specified * description string and a default icon. */ public BuildHL7ResourceAction(String name, AbstractMainFrame mainFrame) { this(name, null, mainFrame); } /** * Defines an <code>Action</code> object with the specified * description string and a the specified icon. */ public BuildHL7ResourceAction(String name, Icon icon, AbstractMainFrame mainFrame) { super(name, icon); this.mainFrame = mainFrame; setActionCommandType(DESKTOP_ACTION_TYPE); } /** * The abstract function that descendant classes must be overridden to * provide customsized handling. * * @param e * @return true if the action is finished successfully; otherwise, * return false. */ protected boolean doAction(ActionEvent e) throws Exception { String resourceName=""; if (getName().equals(COMMAND_BUILD_V2)) resourceName=RESOURCE_NAME_V2; else if (getName().equals(COMMAND_BUILD_V3)) resourceName=RESOURCE_NAME_V3; String resorcePath=BuildResourceUtil.findResourceFile(resourceName); boolean toContinue=false; if (resorcePath==null||resorcePath.equals("")) { toContinue=true; resorcePath=System.getProperty("user.dir")+java.io.File.separator +"lib"+java.io.File.separator +resourceName; } else { String msgConfirm="Your resource is found :"+resorcePath+".\nIt will replaced if you continue ?"; int userReply=JOptionPane.showConfirmDialog(mainFrame, msgConfirm, getName(),JOptionPane.YES_OPTION); if (userReply==JOptionPane.YES_OPTION) toContinue=true; } if (toContinue) { if (getName().equals( COMMAND_BUILD_V3)) new BuildHL7ResourceDialog(mainFrame,getName(),true, resorcePath).setVisible(true); else if (getName().equals( COMMAND_BUILD_V2)) { // V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); - HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V3 Specification" + HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V2 Specification" ,HL7AuthorizationDialog.HL7_V2_WARNING_CONTEXT_FILE_PATH); - DefaultSettings.centerWindow(dialog); - dialog.setViewOnly(true); - dialog.setVisible(true); } else if (getName().equals( COMMAND_BUILD_V2_CORE)) { V2MetaBasicInstallDialog dialog = new V2MetaBasicInstallDialog(mainFrame); DefaultSettings.centerWindow(dialog); //dialog.setViewOnly(true); dialog.setVisible(true); } else if (getName().equals( COMMAND_BUILD_V_MESSAGE)) { V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); // HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V3 Specification" // ,HL7AuthorizationDialog.HL7_V2_WARNING_CONTEXT_FILE_PATH); DefaultSettings.centerWindow(dialog); //dialog.setViewOnly(true); dialog.setVisible(true); } } /* SelectionCollectingMethodDialog selectDialog = new SelectionCollectingMethodDialog(mainFrame); DefaultSettings.centerWindow(selectDialog); selectDialog.setVisible(true); int selected = selectDialog.getSelected(); if (selected == 0) { V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); DefaultSettings.centerWindow(dialog); dialog.setVisible(true); return true; } else if (selected == 1) {} else if (selected == 2) {} else return false; String mtFile = ""; dialog = new V2MetaCollectorForBatchDialog(mainFrame); DefaultSettings.centerWindow(dialog); dialog.setVisible(true); if (!dialog.wasFinished()) return true; int res = JOptionPane.showConfirmDialog(mainFrame, "Do you want to install the collected meta data?", "Install Meta data?", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (res != JOptionPane.YES_OPTION) { return true; } mtFile = dialog.getMessageTypeMetaFilePath(); File file = new File(mtFile); if ((!file.exists())||(!file.isFile())) { JOptionPane.showMessageDialog(mainFrame, "Invalid Message Type File : " + mtFile, "Invalid Message Type File", JOptionPane.ERROR_MESSAGE); return false; } String mtData = FileUtil.readFileIntoString(mtFile); String fName = file.getName(); int idx = fName.indexOf("."); if (idx <= 0) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (1) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } String parDir = file.getParentFile().getAbsolutePath(); if (!parDir.endsWith(File.separator)) parDir = parDir + File.separator; String mtName = fName.substring(0, idx); String mtVersion = fName.substring(idx+1); boolean cTag = false; CheckVersionAndItem check = new CheckVersionAndItem(); for(String ver:check.getVersionTo()) if (mtVersion.equals(ver)) cTag = true; if (!cTag) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (2) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } cTag = false; GroupingMetaInstance group = new GroupingMetaInstance(mtVersion, check.getItemTo()[2]); for (String nam:group.getOutList()) if (mtName.equals(nam)) cTag = true; if (!cTag) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (3) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } File segDir = new File(parDir + mtName); if ((!segDir.exists())||(!segDir.isDirectory())) { JOptionPane.showMessageDialog(mainFrame, "Segment directory is not exist : " + parDir + mtName, "No Segment directory", JOptionPane.ERROR_MESSAGE); return false; } CompareInstance compare = new CompareInstance(path, mtVersion, check.getItemTo()[2]); */ return true; } /** * Return the associated UI component. * * @return the associated UI component. */ protected Component getAssociatedUIComponent() { return mainFrame; } }
false
true
protected boolean doAction(ActionEvent e) throws Exception { String resourceName=""; if (getName().equals(COMMAND_BUILD_V2)) resourceName=RESOURCE_NAME_V2; else if (getName().equals(COMMAND_BUILD_V3)) resourceName=RESOURCE_NAME_V3; String resorcePath=BuildResourceUtil.findResourceFile(resourceName); boolean toContinue=false; if (resorcePath==null||resorcePath.equals("")) { toContinue=true; resorcePath=System.getProperty("user.dir")+java.io.File.separator +"lib"+java.io.File.separator +resourceName; } else { String msgConfirm="Your resource is found :"+resorcePath+".\nIt will replaced if you continue ?"; int userReply=JOptionPane.showConfirmDialog(mainFrame, msgConfirm, getName(),JOptionPane.YES_OPTION); if (userReply==JOptionPane.YES_OPTION) toContinue=true; } if (toContinue) { if (getName().equals( COMMAND_BUILD_V3)) new BuildHL7ResourceDialog(mainFrame,getName(),true, resorcePath).setVisible(true); else if (getName().equals( COMMAND_BUILD_V2)) { // V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V3 Specification" ,HL7AuthorizationDialog.HL7_V2_WARNING_CONTEXT_FILE_PATH); DefaultSettings.centerWindow(dialog); dialog.setViewOnly(true); dialog.setVisible(true); } else if (getName().equals( COMMAND_BUILD_V2_CORE)) { V2MetaBasicInstallDialog dialog = new V2MetaBasicInstallDialog(mainFrame); DefaultSettings.centerWindow(dialog); //dialog.setViewOnly(true); dialog.setVisible(true); } else if (getName().equals( COMMAND_BUILD_V_MESSAGE)) { V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); // HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V3 Specification" // ,HL7AuthorizationDialog.HL7_V2_WARNING_CONTEXT_FILE_PATH); DefaultSettings.centerWindow(dialog); //dialog.setViewOnly(true); dialog.setVisible(true); } } /* SelectionCollectingMethodDialog selectDialog = new SelectionCollectingMethodDialog(mainFrame); DefaultSettings.centerWindow(selectDialog); selectDialog.setVisible(true); int selected = selectDialog.getSelected(); if (selected == 0) { V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); DefaultSettings.centerWindow(dialog); dialog.setVisible(true); return true; } else if (selected == 1) {} else if (selected == 2) {} else return false; String mtFile = ""; dialog = new V2MetaCollectorForBatchDialog(mainFrame); DefaultSettings.centerWindow(dialog); dialog.setVisible(true); if (!dialog.wasFinished()) return true; int res = JOptionPane.showConfirmDialog(mainFrame, "Do you want to install the collected meta data?", "Install Meta data?", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (res != JOptionPane.YES_OPTION) { return true; } mtFile = dialog.getMessageTypeMetaFilePath(); File file = new File(mtFile); if ((!file.exists())||(!file.isFile())) { JOptionPane.showMessageDialog(mainFrame, "Invalid Message Type File : " + mtFile, "Invalid Message Type File", JOptionPane.ERROR_MESSAGE); return false; } String mtData = FileUtil.readFileIntoString(mtFile); String fName = file.getName(); int idx = fName.indexOf("."); if (idx <= 0) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (1) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } String parDir = file.getParentFile().getAbsolutePath(); if (!parDir.endsWith(File.separator)) parDir = parDir + File.separator; String mtName = fName.substring(0, idx); String mtVersion = fName.substring(idx+1); boolean cTag = false; CheckVersionAndItem check = new CheckVersionAndItem(); for(String ver:check.getVersionTo()) if (mtVersion.equals(ver)) cTag = true; if (!cTag) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (2) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } cTag = false; GroupingMetaInstance group = new GroupingMetaInstance(mtVersion, check.getItemTo()[2]); for (String nam:group.getOutList()) if (mtName.equals(nam)) cTag = true; if (!cTag) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (3) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } File segDir = new File(parDir + mtName); if ((!segDir.exists())||(!segDir.isDirectory())) { JOptionPane.showMessageDialog(mainFrame, "Segment directory is not exist : " + parDir + mtName, "No Segment directory", JOptionPane.ERROR_MESSAGE); return false; } CompareInstance compare = new CompareInstance(path, mtVersion, check.getItemTo()[2]); */ return true; }
protected boolean doAction(ActionEvent e) throws Exception { String resourceName=""; if (getName().equals(COMMAND_BUILD_V2)) resourceName=RESOURCE_NAME_V2; else if (getName().equals(COMMAND_BUILD_V3)) resourceName=RESOURCE_NAME_V3; String resorcePath=BuildResourceUtil.findResourceFile(resourceName); boolean toContinue=false; if (resorcePath==null||resorcePath.equals("")) { toContinue=true; resorcePath=System.getProperty("user.dir")+java.io.File.separator +"lib"+java.io.File.separator +resourceName; } else { String msgConfirm="Your resource is found :"+resorcePath+".\nIt will replaced if you continue ?"; int userReply=JOptionPane.showConfirmDialog(mainFrame, msgConfirm, getName(),JOptionPane.YES_OPTION); if (userReply==JOptionPane.YES_OPTION) toContinue=true; } if (toContinue) { if (getName().equals( COMMAND_BUILD_V3)) new BuildHL7ResourceDialog(mainFrame,getName(),true, resorcePath).setVisible(true); else if (getName().equals( COMMAND_BUILD_V2)) { // V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V2 Specification" ,HL7AuthorizationDialog.HL7_V2_WARNING_CONTEXT_FILE_PATH); } else if (getName().equals( COMMAND_BUILD_V2_CORE)) { V2MetaBasicInstallDialog dialog = new V2MetaBasicInstallDialog(mainFrame); DefaultSettings.centerWindow(dialog); //dialog.setViewOnly(true); dialog.setVisible(true); } else if (getName().equals( COMMAND_BUILD_V_MESSAGE)) { V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); // HL7AuthorizationDialog dialog= new HL7AuthorizationDialog (mainFrame,"Notice: Loading HL7 V3 Specification" // ,HL7AuthorizationDialog.HL7_V2_WARNING_CONTEXT_FILE_PATH); DefaultSettings.centerWindow(dialog); //dialog.setViewOnly(true); dialog.setVisible(true); } } /* SelectionCollectingMethodDialog selectDialog = new SelectionCollectingMethodDialog(mainFrame); DefaultSettings.centerWindow(selectDialog); selectDialog.setVisible(true); int selected = selectDialog.getSelected(); if (selected == 0) { V2MetaCollectorDialog dialog = new V2MetaCollectorDialog(mainFrame); DefaultSettings.centerWindow(dialog); dialog.setVisible(true); return true; } else if (selected == 1) {} else if (selected == 2) {} else return false; String mtFile = ""; dialog = new V2MetaCollectorForBatchDialog(mainFrame); DefaultSettings.centerWindow(dialog); dialog.setVisible(true); if (!dialog.wasFinished()) return true; int res = JOptionPane.showConfirmDialog(mainFrame, "Do you want to install the collected meta data?", "Install Meta data?", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (res != JOptionPane.YES_OPTION) { return true; } mtFile = dialog.getMessageTypeMetaFilePath(); File file = new File(mtFile); if ((!file.exists())||(!file.isFile())) { JOptionPane.showMessageDialog(mainFrame, "Invalid Message Type File : " + mtFile, "Invalid Message Type File", JOptionPane.ERROR_MESSAGE); return false; } String mtData = FileUtil.readFileIntoString(mtFile); String fName = file.getName(); int idx = fName.indexOf("."); if (idx <= 0) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (1) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } String parDir = file.getParentFile().getAbsolutePath(); if (!parDir.endsWith(File.separator)) parDir = parDir + File.separator; String mtName = fName.substring(0, idx); String mtVersion = fName.substring(idx+1); boolean cTag = false; CheckVersionAndItem check = new CheckVersionAndItem(); for(String ver:check.getVersionTo()) if (mtVersion.equals(ver)) cTag = true; if (!cTag) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (2) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } cTag = false; GroupingMetaInstance group = new GroupingMetaInstance(mtVersion, check.getItemTo()[2]); for (String nam:group.getOutList()) if (mtName.equals(nam)) cTag = true; if (!cTag) { JOptionPane.showMessageDialog(mainFrame, "Invalid File Name (3) : " + fName, "Invalid File Name", JOptionPane.ERROR_MESSAGE); return false; } File segDir = new File(parDir + mtName); if ((!segDir.exists())||(!segDir.isDirectory())) { JOptionPane.showMessageDialog(mainFrame, "Segment directory is not exist : " + parDir + mtName, "No Segment directory", JOptionPane.ERROR_MESSAGE); return false; } CompareInstance compare = new CompareInstance(path, mtVersion, check.getItemTo()[2]); */ return true; }
diff --git a/src/savant/view/swing/Savant.java b/src/savant/view/swing/Savant.java index 7474793e..d98ff001 100644 --- a/src/savant/view/swing/Savant.java +++ b/src/savant/view/swing/Savant.java @@ -1,2076 +1,2077 @@ /* * Copyright 2009-2011 University of Toronto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package savant.view.swing; import java.awt.*; import java.awt.event.*; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import javax.jnlp.BasicService; import javax.jnlp.ServiceManager; import javax.jnlp.UnavailableServiceException; import javax.swing.*; import com.apple.eawt.*; import com.jidesoft.docking.*; import com.jidesoft.docking.DockingManager.FrameHandle; import com.jidesoft.docking.event.DockableFrameAdapter; import com.jidesoft.docking.event.DockableFrameEvent; import com.jidesoft.plaf.LookAndFeelFactory; import com.jidesoft.plaf.UIDefaultsLookup; import com.jidesoft.plaf.basic.ThemePainter; import com.jidesoft.status.MemoryStatusBarItem; import com.jidesoft.swing.JideSplitPane; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.JDOMException; import savant.api.util.DialogUtils; import savant.controller.*; import savant.controller.event.*; import savant.data.sources.DataSource; import savant.data.types.Genome; import savant.experimental.XMLTool; import savant.plugin.builtin.SAFEDataSourcePlugin; import savant.plugin.builtin.SavantFileRepositoryDataSourcePlugin; import savant.settings.*; import savant.swing.component.TrackChooser; import savant.util.DownloadFile; import savant.util.MiscUtils; import savant.util.Range; import savant.view.dialog.*; import savant.view.icon.SavantIconFactory; import savant.view.tools.ToolsModule; import savant.view.swing.start.StartPanel; import savant.xml.XMLVersion; import savant.xml.XMLVersion.Version; /** * Main application Window (Frame). * * @author mfiume */ public class Savant extends JFrame implements BookmarksChangedListener, ReferenceChangedListener, Listener<ProjectEvent> { private static final Log LOG = LogFactory.getLog(Savant.class); public static boolean turnExperimentalFeaturesOff = true; private static boolean isDebugging = false; private DockingManager auxDockingManager; private JPanel masterPlaceholderPanel; private JPanel trackBackground; private DockingManager trackDockingManager; private JPanel trackPanel; private NavigationBar navigationBar; private ToolsModule savantTools; static boolean showNonGenomicReferenceDialog = true; private static boolean showBookmarksChangedDialog = false; // turned off, its kind of annoying public static final int osSpecificModifier = (MiscUtils.MAC ? java.awt.event.InputEvent.META_MASK : java.awt.event.InputEvent.CTRL_MASK); private DataFormatForm dff; private MemoryStatusBarItem memorystatusbar; private Application macOSXApplication; private boolean browserControlsShown = false; //web start static BasicService basicService = null; static boolean webStart = false; private StartPanel startpage; public void addToolBar(JToolBar b) { this.panel_toolbar.setLayout(new BoxLayout(this.panel_toolbar, BoxLayout.X_AXIS)); this.panel_toolbar.add(b); updateToolBarVisibility(); } public void removeToolBar(JToolBar b) { this.panel_toolbar.remove(b); updateToolBarVisibility(); } private void updateToolBarVisibility() { if (this.panel_toolbar.getComponentCount() == 0) { setToolBarVisibility(false); } else { setToolBarVisibility(true); } } private void setToolBarVisibility(boolean isVisible) { this.panel_toolbar.setVisible(isVisible); this.menuItem_viewtoolbar.setSelected(isVisible); } public Frame addTrackFromFile(String selectedFileName) { URI uri = null; try { uri = new URI(selectedFileName); if (uri.getScheme() == null) { uri = new File(selectedFileName).toURI(); } } catch (URISyntaxException usx) { // This can happen if we're passed a file-name containing spaces. uri = new File(selectedFileName).toURI(); } return addTrackFromURI(uri); } public Frame addTrackFromURI(URI uri) { LOG.info("Loading track " + uri); Frame frame = DockableFrameFactory.createTrackFrame(); //Force a unique frame key. The title of frame is overwritten by track name later. frame.setKey(uri.toString()+System.nanoTime()); TrackFactory.createTrack(uri, frame); addTrackFrame(frame); return frame; } /** * Create a frame for a track (or bundle of tracks) which already exists. * * @param name the name for the new frame * @param tracks the tracks to be added to the frame */ public Frame createFrameForExistingTrack(Track[] tracks) { Frame frame = DockableFrameFactory.createTrackFrame(); frame.setTracks(tracks); LOG.trace("Savant.createFrameForExistingTrack calling trackDockingManager.addFrame"); addTrackFrame(frame); LOG.info("Frame created for track " + frame.getName()); return frame; } /** == [[ DOCKING ]] == * Components (such as frames, the Task Pane, etc.) * can be docked to regions of the UI */ private void initDocking() { masterPlaceholderPanel = new JPanel(); masterPlaceholderPanel.setLayout(new BorderLayout()); this.panel_main.setLayout(new BorderLayout()); this.panel_main.add(masterPlaceholderPanel, BorderLayout.CENTER); auxDockingManager = new DefaultDockingManager(this, masterPlaceholderPanel); masterPlaceholderPanel.setBackground(ColourSettings.getSplitter()); //auxDockingManager.setSidebarRollover(false); auxDockingManager.getWorkspace().setBackground(ColourSettings.getSplitter()); auxDockingManager.setInitSplitPriority(DockingManager.SPLIT_EAST_SOUTH_WEST_NORTH); //auxDockingManager.loadLayoutData(); trackPanel = new JPanel(); trackPanel.setLayout(new BorderLayout()); auxDockingManager.getWorkspace().add(trackPanel, BorderLayout.CENTER); trackDockingManager = new DefaultDockingManager(this, trackPanel); trackPanel.setBackground(ColourSettings.getSplitter()); trackDockingManager.getWorkspace().setBackground(ColourSettings.getSplitter()); //trackDockingManager.setSidebarRollover(false); trackDockingManager.getWorkspace().setBackground(Color.red); trackDockingManager.setInitNorthSplit(JideSplitPane.VERTICAL_SPLIT); //trackDockingManager.loadLayoutData(); auxDockingManager.setShowInitial(false); trackDockingManager.setShowInitial(false); auxDockingManager.loadLayoutData(); trackDockingManager.loadLayoutData(); rangeSelector = new RangeSelectionPanel(); rangeSelector.setPreferredSize(new Dimension(10000, 23)); rangeSelector.setMaximumSize(new Dimension(10000, 23)); rangeController.addRangeChangedListener(rangeSelector); rangeSelector.setVisible(false); referenceCombo = new ReferenceCombo(); referenceCombo.setVisible(false); ruler = new Ruler(); ruler.setPreferredSize(new Dimension(10000, 23)); ruler.setMaximumSize(new Dimension(10000, 23)); ruler.setVisible(false); Box box1 = new Box(BoxLayout.LINE_AXIS) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(RangeSelectionPanel.LINE_COLOUR); int capPos = ruler.getLeftCapPos() + Ruler.CAP_IMAGE_WIDTH; g.drawLine(capPos, getHeight() - 1, rangeSelector.getX(), getHeight() - 1); } }; box1.add(referenceCombo); box1.add(rangeSelector); Box box2 = Box.createVerticalBox(); box2.add(box1); box2.add(ruler); trackPanel.add(box2, BorderLayout.NORTH); trackBackground = new JPanel(); trackBackground.setBackground(Color.darkGray); trackBackground.setLayout(new BorderLayout()); trackDockingManager.getWorkspace().add(trackBackground); trackDockingManager.addDockableFrameListener(new DockableFrameAdapter() { @Override public void dockableFrameRemoved(DockableFrameEvent arg0) { FrameController.getInstance().closeFrame((Frame)arg0.getDockableFrame()); } @Override public void dockableFrameActivated(DockableFrameEvent arg0) { ((Frame)arg0.getDockableFrame()).setActiveFrame(); } @Override public void dockableFrameDeactivated(DockableFrameEvent arg0) { ((Frame)arg0.getDockableFrame()).setInactiveFrame(); } }); trackDockingManager.setAllowedDockSides(DockContext.DOCK_SIDE_HORIZONTAL); // make sure only one active frame addDockingManagerToGroup(auxDockingManager); addDockingManagerToGroup(trackDockingManager); } /** Minimum and maximum dimensions of the browser form */ static int minimumFormWidth = 500; static int minimumFormHeight = 500; /** The loaded genome */ //private Genome loadedGenome; /** The log */ private static JTextArea log; private ReferenceCombo referenceCombo; /** Click and drag control for range selection */ private RangeSelectionPanel rangeSelector; private Ruler ruler; /** Information & Analysis Tabbed Pane (for plugin use) */ private JTabbedPane auxTabbedPane; /** * Info */ private static BookmarkSheet favoriteSheet; private RangeController rangeController = RangeController.getInstance(); private BookmarkController favoriteController = BookmarkController.getInstance(); private SelectionController selectionController = SelectionController.getInstance(); private static Savant instance = null; public static synchronized Savant getInstance() { if (instance == null) { instance = new Savant(); ProjectController.getInstance().addListener(instance); } return instance; } /** Creates new form Savant */ private Savant() { try { basicService = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService"); webStart = true; } catch (UnavailableServiceException e) { //System.err.println("Lookup failed: " + e); webStart = false; } instance = this; Splash s = new Splash(instance, false); s.setVisible(true); loadPreferences(); //removeTmpFiles(); addComponentListener(new ComponentAdapter() { /** * Resize the form to the minimum size if the * user has resized it to something smaller. * @param e The resize event */ @Override public void componentResized(ComponentEvent e) { int width = getWidth(); int height = getHeight(); //we check if either the width //or the height are below minimum boolean resize = false; if (width < minimumFormWidth) { resize = true; width = minimumFormWidth; } if (height < minimumFormHeight) { resize = true; height = minimumFormHeight; } if (resize) { setSize(width, height); } } }); s.setStatus("Initializing GUI"); initComponents(); customizeUI(); init(); if (BrowserSettings.getCheckVersionOnStartup()) { s.setStatus("Checking version"); checkVersion(); } if (BrowserSettings.getCollectAnonymousUsage()) { logUsageStats(); } s.setStatus("Loading plugins"); PluginController pc = PluginController.getInstance(); if (DataSourcePluginController.getInstance().hasOnlySavantRepoDataSource()) { loadFromDataSourcePlugin.setText("Load Track from Repository..."); } s.setStatus("Organizing layout"); displayAuxPanels(); if (turnExperimentalFeaturesOff) { disableExperimentalFeatures(); } s.setVisible(false); makeGUIVisible(); } private void initXMLTools() { try { File dir = DirectorySettings.getXMLToolDescriptionsDirectory(); for (File f : dir.listFiles()) { if (f.getName().toLowerCase().endsWith(".xml")) { ToolsModule.addTool(new XMLTool(f)); } } } catch (IOException ex) { } catch (JDOMException ex) { } } /** 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { view_buttongroup = new javax.swing.ButtonGroup(); panel_top = new javax.swing.JPanel(); panelExtendedMiddle = new javax.swing.JPanel(); panel_main = new javax.swing.JPanel(); toolbar_bottom = new javax.swing.JToolBar(); label_mouseposition_title = new javax.swing.JLabel(); label_mouseposition = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); label_status = new javax.swing.JLabel(); s_e_sep = new javax.swing.JToolBar.Separator(); label_memory = new javax.swing.JLabel(); panel_toolbar = new javax.swing.JPanel(); menuBar_top = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); loadGenomeItem = new javax.swing.JMenuItem(); loadFromFileItem = new javax.swing.JMenuItem(); loadFromURLItem = new javax.swing.JMenuItem(); loadFromDataSourcePlugin = new javax.swing.JMenuItem(); recentTrackMenu = new javax.swing.JMenu(); javax.swing.JPopupMenu.Separator jSeparator1 = new javax.swing.JPopupMenu.Separator(); openProjectItem = new javax.swing.JMenuItem(); recentProjectMenu = new javax.swing.JMenu(); saveProjectItem = new javax.swing.JMenuItem(); saveProjectAsItem = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator2 = new javax.swing.JPopupMenu.Separator(); formatItem = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator3 = new javax.swing.JPopupMenu.Separator(); exportItem = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); exitItem = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); menuitem_undo = new javax.swing.JMenuItem(); menuitem_redo = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator6 = new javax.swing.JPopupMenu.Separator(); menuItemAddToFaves = new javax.swing.JMenuItem(); menuitem_deselectall = new javax.swing.JMenuItem(); jSeparator7 = new javax.swing.JPopupMenu.Separator(); menuitem_preferences = new javax.swing.JMenuItem(); viewMenu = new javax.swing.JMenu(); menuItemPanLeft = new javax.swing.JMenuItem(); menuItemPanRight = new javax.swing.JMenuItem(); menuItemZoomIn = new javax.swing.JMenuItem(); menuItemZoomOut = new javax.swing.JMenuItem(); menuItemShiftStart = new javax.swing.JMenuItem(); menuItemShiftEnd = new javax.swing.JMenuItem(); javax.swing.JSeparator jSeparator8 = new javax.swing.JSeparator(); menuitem_aim = new javax.swing.JCheckBoxMenuItem(); menuitem_view_plumbline = new javax.swing.JCheckBoxMenuItem(); menuitem_view_spotlight = new javax.swing.JCheckBoxMenuItem(); windowMenu = new javax.swing.JMenu(); menuItem_viewRangeControls = new javax.swing.JCheckBoxMenuItem(); menuitem_genomeview = new javax.swing.JCheckBoxMenuItem(); menuitem_ruler = new javax.swing.JCheckBoxMenuItem(); menuItem_viewtoolbar = new javax.swing.JCheckBoxMenuItem(); menuitem_statusbar = new javax.swing.JCheckBoxMenuItem(); speedAndEfficiencyItem = new javax.swing.JCheckBoxMenuItem(); javax.swing.JSeparator jSeparator9 = new javax.swing.JSeparator(); menuitem_startpage = new javax.swing.JCheckBoxMenuItem(); menuitem_tools = new javax.swing.JCheckBoxMenuItem(); menu_bookmarks = new javax.swing.JCheckBoxMenuItem(); pluginsMenu = new javax.swing.JMenu(); menuitem_pluginmanager = new javax.swing.JMenuItem(); jSeparator10 = new javax.swing.JPopupMenu.Separator(); helpMenu = new javax.swing.JMenu(); userManualItem = new javax.swing.JMenuItem(); tutorialsItem = new javax.swing.JMenuItem(); javax.swing.JMenuItem checkForUpdatesItem = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); javax.swing.JSeparator jSeparator11 = new javax.swing.JSeparator(); websiteItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 204)); panel_top.setMaximumSize(new java.awt.Dimension(1000, 30)); panel_top.setMinimumSize(new java.awt.Dimension(0, 0)); panel_top.setPreferredSize(new java.awt.Dimension(0, 30)); panel_top.setLayout(new java.awt.BorderLayout()); panelExtendedMiddle.setBackground(new java.awt.Color(51, 51, 51)); panelExtendedMiddle.setMinimumSize(new java.awt.Dimension(0, 0)); panelExtendedMiddle.setPreferredSize(new java.awt.Dimension(990, 25)); javax.swing.GroupLayout panelExtendedMiddleLayout = new javax.swing.GroupLayout(panelExtendedMiddle); panelExtendedMiddle.setLayout(panelExtendedMiddleLayout); panelExtendedMiddleLayout.setHorizontalGroup( panelExtendedMiddleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panelExtendedMiddleLayout.setVerticalGroup( panelExtendedMiddleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); panel_top.add(panelExtendedMiddle, java.awt.BorderLayout.CENTER); panel_main.setBackground(new java.awt.Color(153, 153, 153)); panel_main.setMaximumSize(new java.awt.Dimension(99999, 99999)); panel_main.setMinimumSize(new java.awt.Dimension(1, 1)); panel_main.setPreferredSize(new java.awt.Dimension(99999, 99999)); javax.swing.GroupLayout panel_mainLayout = new javax.swing.GroupLayout(panel_main); panel_main.setLayout(panel_mainLayout); panel_mainLayout.setHorizontalGroup( panel_mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panel_mainLayout.setVerticalGroup( panel_mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 526, Short.MAX_VALUE) ); toolbar_bottom.setFloatable(false); toolbar_bottom.setAlignmentX(1.0F); label_mouseposition_title.setText(" Position: "); toolbar_bottom.add(label_mouseposition_title); label_mouseposition.setText("mouse over track"); toolbar_bottom.add(label_mouseposition); jLabel1.setText("Time: "); toolbar_bottom.add(jLabel1); label_status.setMaximumSize(new java.awt.Dimension(300, 14)); label_status.setMinimumSize(new java.awt.Dimension(100, 14)); label_status.setPreferredSize(new java.awt.Dimension(100, 14)); toolbar_bottom.add(label_status); toolbar_bottom.add(s_e_sep); label_memory.setText(" Memory: "); toolbar_bottom.add(label_memory); panel_toolbar.setVisible(false); panel_toolbar.setPreferredSize(new java.awt.Dimension(856, 24)); javax.swing.GroupLayout panel_toolbarLayout = new javax.swing.GroupLayout(panel_toolbar); panel_toolbar.setLayout(panel_toolbarLayout); panel_toolbarLayout.setHorizontalGroup( panel_toolbarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panel_toolbarLayout.setVerticalGroup( panel_toolbarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 24, Short.MAX_VALUE) ); fileMenu.setText("File"); loadGenomeItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK)); loadGenomeItem.setText("Load Genome..."); loadGenomeItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadGenomeItemActionPerformed(evt); } }); fileMenu.add(loadGenomeItem); loadFromFileItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); loadFromFileItem.setText("Load Track from File..."); loadFromFileItem.setEnabled(false); loadFromFileItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromFileItemActionPerformed(evt); } }); fileMenu.add(loadFromFileItem); loadFromURLItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_MASK)); loadFromURLItem.setText("Load Track from URL..."); loadFromURLItem.setEnabled(false); loadFromURLItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromURLItemActionPerformed(evt); } }); fileMenu.add(loadFromURLItem); loadFromDataSourcePlugin.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); loadFromDataSourcePlugin.setText("Load Track from Other Datasource..."); loadFromDataSourcePlugin.setEnabled(false); loadFromDataSourcePlugin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromDataSourcePluginActionPerformed(evt); } }); fileMenu.add(loadFromDataSourcePlugin); recentTrackMenu.setText("Load Recent Track"); fileMenu.add(recentTrackMenu); fileMenu.add(jSeparator1); openProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); + openProjectItem.setText("Open Project..."); openProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openProjectItemActionPerformed(evt); } }); fileMenu.add(openProjectItem); recentProjectMenu.setText("Open Recent Project"); fileMenu.add(recentProjectMenu); saveProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); saveProjectItem.setText("Save Project"); saveProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveProjectItemActionPerformed(evt); } }); fileMenu.add(saveProjectItem); saveProjectAsItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveProjectAsItem.setText("Save Project As..."); saveProjectAsItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveProjectAsItemActionPerformed(evt); } }); fileMenu.add(saveProjectAsItem); fileMenu.add(jSeparator2); formatItem.setText("Format Text File..."); formatItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { formatItemActionPerformed(evt); } }); fileMenu.add(formatItem); fileMenu.add(jSeparator3); exportItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK)); exportItem.setText("Export Track Images..."); exportItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_exportActionPerformed(evt); } }); fileMenu.add(exportItem); fileMenu.add(jSeparator4); exitItem.setText("Exit"); exitItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitItemActionPerformed(evt); } }); fileMenu.add(exitItem); menuBar_top.add(fileMenu); editMenu.setText("Edit"); menuitem_undo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK)); menuitem_undo.setText("Undo Range Change"); menuitem_undo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_undoActionPerformed(evt); } }); editMenu.add(menuitem_undo); menuitem_redo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK)); menuitem_redo.setText("Redo Range Change"); menuitem_redo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_redoActionPerformed(evt); } }); editMenu.add(menuitem_redo); editMenu.add(jSeparator6); menuItemAddToFaves.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK)); menuItemAddToFaves.setText("Bookmark"); menuItemAddToFaves.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemAddToFavesActionPerformed(evt); } }); editMenu.add(menuItemAddToFaves); menuitem_deselectall.setText("Deselect All"); menuitem_deselectall.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_deselectActionPerformed(evt); } }); editMenu.add(menuitem_deselectall); editMenu.add(jSeparator7); menuitem_preferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); menuitem_preferences.setText("Preferences"); menuitem_preferences.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_preferencesActionPerformed(evt); } }); editMenu.add(menuitem_preferences); menuBar_top.add(editMenu); viewMenu.setText("View"); menuItemPanLeft.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanLeft.setText("Pan Left"); menuItemPanLeft.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemPanLeftActionPerformed(evt); } }); viewMenu.add(menuItemPanLeft); menuItemPanRight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanRight.setText("Pan Right"); menuItemPanRight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemPanRightActionPerformed(evt); } }); viewMenu.add(menuItemPanRight); menuItemZoomIn.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomIn.setText("Zoom In"); menuItemZoomIn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemZoomInActionPerformed(evt); } }); viewMenu.add(menuItemZoomIn); menuItemZoomOut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomOut.setText("Zoom Out"); menuItemZoomOut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemZoomOutActionPerformed(evt); } }); viewMenu.add(menuItemZoomOut); menuItemShiftStart.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0)); menuItemShiftStart.setText("Shift to Start"); menuItemShiftStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemShiftStartActionPerformed(evt); } }); viewMenu.add(menuItemShiftStart); menuItemShiftEnd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_END, 0)); menuItemShiftEnd.setText("Shift to End"); menuItemShiftEnd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemShiftEndActionPerformed(evt); } }); viewMenu.add(menuItemShiftEnd); viewMenu.add(jSeparator8); menuitem_aim.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, java.awt.event.InputEvent.CTRL_MASK)); menuitem_aim.setText("Crosshair"); menuitem_aim.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_aimActionPerformed(evt); } }); viewMenu.add(menuitem_aim); menuitem_view_plumbline.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK)); menuitem_view_plumbline.setText("Plumbline"); menuitem_view_plumbline.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_view_plumblineActionPerformed(evt); } }); viewMenu.add(menuitem_view_plumbline); menuitem_view_spotlight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK)); menuitem_view_spotlight.setText("Spotlight"); menuitem_view_spotlight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_view_spotlightActionPerformed(evt); } }); viewMenu.add(menuitem_view_spotlight); menuBar_top.add(viewMenu); windowMenu.setText("Window"); windowMenu.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { windowMenuStateChanged(evt); } }); menuItem_viewRangeControls.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuItem_viewRangeControls.setText("Navigation"); menuItem_viewRangeControls.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItem_viewRangeControlsMousePressed(evt); } }); windowMenu.add(menuItem_viewRangeControls); menuitem_genomeview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_genomeview.setText("Genome"); menuitem_genomeview.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_genomeviewActionPerformed(evt); } }); windowMenu.add(menuitem_genomeview); menuitem_ruler.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_ruler.setText("Ruler"); menuitem_ruler.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_rulerActionPerformed(evt); } }); windowMenu.add(menuitem_ruler); menuItem_viewtoolbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuItem_viewtoolbar.setText("Plugin Toolbar"); menuItem_viewtoolbar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItem_viewtoolbarActionPerformed(evt); } }); windowMenu.add(menuItem_viewtoolbar); menuitem_statusbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_statusbar.setSelected(true); menuitem_statusbar.setText("Status Bar"); menuitem_statusbar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_statusbarActionPerformed(evt); } }); windowMenu.add(menuitem_statusbar); speedAndEfficiencyItem.setText("Resources"); speedAndEfficiencyItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { speedAndEfficiencyItemActionPerformed(evt); } }); windowMenu.add(speedAndEfficiencyItem); windowMenu.add(jSeparator9); menuitem_startpage.setSelected(true); menuitem_startpage.setText("Start Page"); menuitem_startpage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_startpageActionPerformed(evt); } }); windowMenu.add(menuitem_startpage); menuitem_tools.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_tools.setText("Tools"); menuitem_tools.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_toolsActionPerformed(evt); } }); windowMenu.add(menuitem_tools); menu_bookmarks.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menu_bookmarks.setText("Bookmarks"); menu_bookmarks.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_bookmarksActionPerformed(evt); } }); windowMenu.add(menu_bookmarks); menuBar_top.add(windowMenu); pluginsMenu.setText("Plugins"); menuitem_pluginmanager.setText("Plugin Manager"); menuitem_pluginmanager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_pluginmanagerActionPerformed(evt); } }); pluginsMenu.add(menuitem_pluginmanager); pluginsMenu.add(jSeparator10); menuBar_top.add(pluginsMenu); helpMenu.setText("Help"); userManualItem.setText("Manuals"); userManualItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { userManualItemActionPerformed(evt); } }); helpMenu.add(userManualItem); tutorialsItem.setText("Video Tutorials"); tutorialsItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tutorialsItemActionPerformed(evt); } }); helpMenu.add(tutorialsItem); checkForUpdatesItem.setText("Check for updates"); checkForUpdatesItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkForUpdatesItemActionPerformed(evt); } }); helpMenu.add(checkForUpdatesItem); jMenuItem2.setText("Report an issue"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); helpMenu.add(jMenuItem2); jMenuItem1.setText("Request a feature"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); helpMenu.add(jMenuItem1); helpMenu.add(jSeparator11); websiteItem.setText("Website"); websiteItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { websiteItemActionPerformed(evt); } }); helpMenu.add(websiteItem); menuBar_top.add(helpMenu); setJMenuBar(menuBar_top); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel_top, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(toolbar_bottom, javax.swing.GroupLayout.DEFAULT_SIZE, 997, Short.MAX_VALUE) .addContainerGap()) .addComponent(panel_toolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) .addComponent(panel_main, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(panel_top, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(panel_toolbar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(panel_main, javax.swing.GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(toolbar_bottom, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Shift the currentViewableRange all the way to the right * @param evt The mouse event which triggers the function */ /** * Shift the currentViewableRange to the right * @param evt The mouse event which triggers the function */ /** * Shift the currentViewableRange to the left * @param evt The mouse event which triggers the function */ /** * Shift the currentViewableRange all the way to the left * @param evt The mouse event which triggers the function */ private void menuItem_viewRangeControlsMousePressed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_viewRangeControlsMousePressed this.panel_top.setVisible(!this.panel_top.isVisible()); }//GEN-LAST:event_menuItem_viewRangeControlsMousePressed private void menuItemZoomInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemZoomInActionPerformed RangeController rc = RangeController.getInstance(); rc.zoomIn(); }//GEN-LAST:event_menuItemZoomInActionPerformed private void menuItemZoomOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemZoomOutActionPerformed RangeController rc = RangeController.getInstance(); rc.zoomOut(); }//GEN-LAST:event_menuItemZoomOutActionPerformed private void menuItemPanLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemPanLeftActionPerformed RangeController rc = RangeController.getInstance(); rc.shiftRangeLeft(); }//GEN-LAST:event_menuItemPanLeftActionPerformed private void menuItemPanRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemPanRightActionPerformed RangeController rc = RangeController.getInstance(); rc.shiftRangeRight(); }//GEN-LAST:event_menuItemPanRightActionPerformed private void menuitem_undoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_undoActionPerformed RangeController rc = RangeController.getInstance(); rc.undoRangeChange(); }//GEN-LAST:event_menuitem_undoActionPerformed private void menuitem_redoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_redoActionPerformed RangeController rc = RangeController.getInstance(); rc.redoRangeChange(); }//GEN-LAST:event_menuitem_redoActionPerformed private void menuItemAddToFavesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemAddToFavesActionPerformed BookmarkController fc = BookmarkController.getInstance(); fc.addCurrentRangeToBookmarks(); }//GEN-LAST:event_menuItemAddToFavesActionPerformed private void formatItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_formatItemActionPerformed if (!dff.isVisible()) { LOG.info("Showing format form..."); dff.clear(); dff.setLocationRelativeTo(this); dff.setVisible(true); } }//GEN-LAST:event_formatItemActionPerformed private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed Savant.getInstance().askToDispose(); }//GEN-LAST:event_exitItemActionPerformed private void loadGenomeItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadGenomeItemActionPerformed showOpenGenomeDialog(); }//GEN-LAST:event_loadGenomeItemActionPerformed private void loadFromFileItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadFromFileItemActionPerformed if (!ReferenceController.getInstance().isGenomeLoaded()) { JOptionPane.showMessageDialog(this, "Load a genome first."); return; } File[] selectedFiles = DialogUtils.chooseFilesForOpen("Open Tracks", null, null); for (File f : selectedFiles) { // This creates the tracks asynchronously, which handles all exceptions internally. addTrackFromFile(f.getAbsolutePath()); } }//GEN-LAST:event_loadFromFileItemActionPerformed private void loadFromURLItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadFromURLItemActionPerformed URL url = OpenURLDialog.getURL(this); if (url != null) { try { addTrackFromURI(url.toURI()); } catch (URISyntaxException ignored) { } } }//GEN-LAST:event_loadFromURLItemActionPerformed private void websiteItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_websiteItemActionPerformed try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(BrowserSettings.URL)); } catch (IOException ex) { LOG.error("Unable to access Savant website", ex); } }//GEN-LAST:event_websiteItemActionPerformed private void menuitem_pluginmanagerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_pluginmanagerActionPerformed PluginManagerDialog pd = PluginManagerDialog.getInstance(); pd.setLocationRelativeTo(this); pd.setVisible(true); }//GEN-LAST:event_menuitem_pluginmanagerActionPerformed private void menuitem_view_plumblineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_view_plumblineActionPerformed GraphPaneController gpc = GraphPaneController.getInstance(); gpc.setPlumbing(this.menuitem_view_plumbline.isSelected()); }//GEN-LAST:event_menuitem_view_plumblineActionPerformed public void setPlumbingMenutItemSelected(boolean isSelected) { this.menuitem_view_plumbline.setSelected(isSelected); } public void setSpotlightMenutItemSelected(boolean isSelected) { this.menuitem_view_spotlight.setSelected(isSelected); } public void setCrosshairMenutItemSelected(boolean isSelected) { this.menuitem_aim.setSelected(isSelected); } private void menuitem_view_spotlightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_view_spotlightActionPerformed GraphPaneController gpc = GraphPaneController.getInstance(); gpc.setSpotlight(this.menuitem_view_spotlight.isSelected()); }//GEN-LAST:event_menuitem_view_spotlightActionPerformed private void windowMenuStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_windowMenuStateChanged /* if(this.getAuxDockingManager().getFrame("Information & Analysis").isVisible() != this.menu_info.getState()){ this.menu_info.setState(!this.menu_info.getState()); } if(this.getAuxDockingManager().getFrame("Bookmarks").isVisible() != this.menu_bookmarks.getState()){ this.menu_bookmarks.setState(!this.menu_bookmarks.getState()); } */ }//GEN-LAST:event_windowMenuStateChanged private void menu_bookmarksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_bookmarksActionPerformed String frameKey = "Bookmarks"; DockingManager m = this.getAuxDockingManager(); boolean isVisible = m.getFrame(frameKey).isHidden(); MiscUtils.setFrameVisibility(frameKey, isVisible, m); this.menu_bookmarks.setSelected(isVisible); }//GEN-LAST:event_menu_bookmarksActionPerformed private void tutorialsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tutorialsItemActionPerformed try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(BrowserSettings.MEDIA_URL)); } catch (IOException ex) { LOG.error("Unable to access online tutorials.", ex); } }//GEN-LAST:event_tutorialsItemActionPerformed private void userManualItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userManualItemActionPerformed try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(BrowserSettings.DOCUMENTATION_URL)); } catch (IOException ex) { LOG.error("Unable to access online user manual.", ex); } }//GEN-LAST:event_userManualItemActionPerformed private void menuitem_rulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_rulerActionPerformed this.ruler.setVisible(!this.ruler.isVisible()); }//GEN-LAST:event_menuitem_rulerActionPerformed private void menuitem_genomeviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_genomeviewActionPerformed boolean flag = !rangeSelector.isVisible(); rangeSelector.setVisible(flag); referenceCombo.setVisible(flag); }//GEN-LAST:event_menuitem_genomeviewActionPerformed private void menuitem_statusbarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_statusbarActionPerformed this.toolbar_bottom.setVisible(!this.toolbar_bottom.isVisible()); }//GEN-LAST:event_menuitem_statusbarActionPerformed private void menuitem_exportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_exportActionPerformed //ExportImageDialog export = new ExportImageDialog(Savant.getInstance(), true); //export.setVisible(true); ExportImage unused = new ExportImage(); }//GEN-LAST:event_menuitem_exportActionPerformed private void menuItemShiftStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemShiftStartActionPerformed rangeController.shiftRangeFarLeft(); }//GEN-LAST:event_menuItemShiftStartActionPerformed private void menuItemShiftEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemShiftEndActionPerformed rangeController.shiftRangeFarRight(); }//GEN-LAST:event_menuItemShiftEndActionPerformed static boolean arePreferencesInitialized = false; private void menuitem_preferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_preferencesActionPerformed if (!arePreferencesInitialized) { SettingsDialog.addSection(new ColourSchemeSettingsSection()); SettingsDialog.addSection(new TemporaryFilesSettingsSection()); SettingsDialog.addSection(new GeneralSettingsSection()); SettingsDialog.addSection(new RemoteFilesSettingsSection()); SettingsDialog.addSection(new ResolutionSettingsSection()); SettingsDialog.addSection(new DisplaySettingsSection()); arePreferencesInitialized = true; } SettingsDialog.showOptionsDialog(this); }//GEN-LAST:event_menuitem_preferencesActionPerformed private void menuitem_toolsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_toolsActionPerformed String frameKey = "Tools"; DockingManager m = this.getAuxDockingManager(); boolean isVisible = m.getFrame(frameKey).isHidden(); MiscUtils.setFrameVisibility(frameKey, isVisible, m); this.menuitem_tools.setSelected(isVisible); }//GEN-LAST:event_menuitem_toolsActionPerformed private void menuitem_deselectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_deselectActionPerformed SelectionController.getInstance().removeAll(); }//GEN-LAST:event_menuitem_deselectActionPerformed private void saveProjectAsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectAsItemActionPerformed ProjectController.getInstance().promptUserToSaveProjectAs(); }//GEN-LAST:event_saveProjectAsItemActionPerformed private void openProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openProjectItemActionPerformed try { ProjectController.getInstance().promptUserToLoadProject(); } catch (Exception x) { DialogUtils.displayException("Savant", "Unable to open project.", x); } }//GEN-LAST:event_openProjectItemActionPerformed private void checkForUpdatesItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkForUpdatesItemActionPerformed checkVersion(true); }//GEN-LAST:event_checkForUpdatesItemActionPerformed private void saveProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectItemActionPerformed try { ProjectController.getInstance().promptUserToSaveSession(); } catch (Exception x) { DialogUtils.displayException("Savant", "Unable to save project.", x); } }//GEN-LAST:event_saveProjectItemActionPerformed private void menuItem_viewtoolbarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_viewtoolbarActionPerformed this.setToolBarVisibility(menuItem_viewtoolbar.isSelected()); }//GEN-LAST:event_menuItem_viewtoolbarActionPerformed private void speedAndEfficiencyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_speedAndEfficiencyItemActionPerformed setSpeedAndEfficiencyIndicatorsVisible(speedAndEfficiencyItem.isSelected()); }//GEN-LAST:event_speedAndEfficiencyItemActionPerformed private void menuitem_aimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_aimActionPerformed GraphPaneController gpc = GraphPaneController.getInstance(); gpc.setAiming(this.menuitem_aim.isSelected()); }//GEN-LAST:event_menuitem_aimActionPerformed private void menuitem_startpageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitem_startpageActionPerformed setStartPageVisible(this.menuitem_startpage.isSelected()); }//GEN-LAST:event_menuitem_startpageActionPerformed private void loadFromDataSourcePluginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadFromDataSourcePluginActionPerformed try { DataSource s = DataSourcePluginDialog.getDataSource(this); if (s != null) { Track t = TrackFactory.createTrack(s); createFrameForExistingTrack(new Track[] { t }); } } catch (Exception x) { LOG.error("Unable to create track from DataSource plugin", x); DialogUtils.displayException("Track Creation Failed", "Unable to create track.", x); } }//GEN-LAST:event_loadFromDataSourcePluginActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed (new FeatureRequestDialog(this,false)).setVisible(true); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed (new BugReportDialog(this,false)).setVisible(true); }//GEN-LAST:event_jMenuItem2ActionPerformed /** * Starts an instance of the Savant Browser * @param args the command line arguments */ public static void main(String args[]) throws Exception { boolean loadProject = false; boolean loadPlugin = false; String loadProjectUrl = null; List<String> loadPluginUrls = new ArrayList<String>(); for(int i = 0; i < args.length; i++){ String s = args[i]; if(s.startsWith("--")){ //build loadProject = false; loadPlugin = false; BrowserSettings.build = s.replaceAll("-", ""); if (s.equals("--debug")) { turnExperimentalFeaturesOff = false; } } else if (s.startsWith("-")){ if(s.equals("-project")){ loadProject = true; loadPlugin = false; } else if (s.equals("-plugins")){ loadPlugin = true; loadProject = false; } } else if (loadProject){ loadProjectUrl = s; loadProject = false; } else if (loadPlugin){ loadPluginUrls.add(s); } else { //bad argument, skip } } installMissingPlugins(loadPluginUrls); //java.awt.EventQueue.invokeLater(new Runnable() { //@Override //public void run() { System.setProperty("apple.laf.useScreenMenuBar", "true"); com.jidesoft.utils.Lm.verifyLicense("Marc Fiume", "Savant Genome Browser", "1BimsQGmP.vjmoMbfkPdyh0gs3bl3932"); LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2007_STYLE); try { UIManager.put("JideSplitPaneDivider.border", 5); // Set System L&F UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE_WITHOUT_MENU); // LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE); } catch (Exception e) { // handle exception } Savant instance = Savant.getInstance(); //load project immediately if argument exists if (instance.isWebStart() && loadProjectUrl != null){ ProjectController.getInstance().loadProjectFromURL(loadProjectUrl); } } public static void loadPreferences() { } public static void checkVersion() { checkVersion(false); } private static String getPost(String name, String value) { return name + "=" + value; } private static void logUsageStats() { try { URL url; URLConnection urlConn; DataOutputStream printout; // URL of CGI-Bin script. url = new URL(BrowserSettings.LOG_USAGE_STATS_URL); // URL connection channel. urlConn = url.openConnection(); // Let the run-time system (RTS) know that we want input. urlConn.setDoInput(true); // Let the RTS know that we want to do output. urlConn.setDoOutput(true); // No caching, we want the real thing. urlConn.setUseCaches(false); // Specify the content type. urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); Locale locale = Locale.getDefault(); String content = post("time", dateFormat.format(date)) + "&" + post("language", locale.getDisplayLanguage()) + "&" + post("user.timezone", System.getProperty("user.timezone")) + "&" + post("savant.version", BrowserSettings.version) + "&" + post("savant.build", BrowserSettings.build) //+ "&" + post("address", InetAddress.getLocalHost().getHostAddress()) + "&" + post("java.version", System.getProperty("java.version")) + "&" + post("java.vendor", System.getProperty("java.vendor")) + "&" + post("os.name", System.getProperty("os.name")) + "&" + post("os.arch", System.getProperty("os.arch")) + "&" + post("os.version", System.getProperty("os.version")) + "&" + post("user.region", System.getProperty("user.region") ); printout.writeBytes(content); printout.flush(); printout.close(); urlConn.getInputStream(); } catch (Exception ex) { //LOG.error("Error logging usage stats.", ex); } } private static String post(String id, String msg) { return id + "=" + id + ":" + ((msg == null) ? "null" : URLEncoder.encode(msg)); } public static void checkVersion(boolean verbose) { try { File versionFile = DownloadFile.downloadFile(new URL(BrowserSettings.VERSION_URL), DirectorySettings.getSavantDirectory()); if (versionFile != null) { LOG.info("Saved version file to: " + versionFile.getAbsolutePath()); Version currentversion = (new XMLVersion(versionFile)).getVersion(); Version thisversion = new Version(BrowserSettings.version); if (currentversion.compareTo(thisversion) > 0) { DialogUtils.displayMessage("Savant", "A new version of Savant (" + currentversion.toString() + ") is available.\n" + "To stop this message from appearing, download the newest version at " + BrowserSettings.URL + "\nor disable automatic " + "checking in Preferences."); } else { if (verbose) { DialogUtils.displayMessage("Savant", "This version of Savant (" + thisversion.toString() + ") is up to date."); } } } else { if (verbose) { DialogUtils.displayMessage("Savant Warning", "Could not connect to server. Please ensure you have connection to the internet and try again."); } LOG.error("Error downloading version file"); } versionFile.delete(); } catch (IOException ex) { } catch (JDOMException ex) { } catch (NullPointerException ex) { } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu editMenu; private javax.swing.JMenuItem exitItem; private javax.swing.JMenuItem exportItem; private javax.swing.JMenu fileMenu; private javax.swing.JMenuItem formatItem; private javax.swing.JMenu helpMenu; private javax.swing.JLabel jLabel1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JPopupMenu.Separator jSeparator10; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator7; private javax.swing.JLabel label_memory; private javax.swing.JLabel label_mouseposition; private javax.swing.JLabel label_mouseposition_title; private javax.swing.JLabel label_status; private javax.swing.JMenuItem loadFromDataSourcePlugin; private javax.swing.JMenuItem loadFromFileItem; private javax.swing.JMenuItem loadFromURLItem; private javax.swing.JMenuItem loadGenomeItem; private javax.swing.JMenuBar menuBar_top; private javax.swing.JMenuItem menuItemAddToFaves; private javax.swing.JMenuItem menuItemPanLeft; private javax.swing.JMenuItem menuItemPanRight; private javax.swing.JMenuItem menuItemShiftEnd; private javax.swing.JMenuItem menuItemShiftStart; private javax.swing.JMenuItem menuItemZoomIn; private javax.swing.JMenuItem menuItemZoomOut; private javax.swing.JCheckBoxMenuItem menuItem_viewRangeControls; private javax.swing.JCheckBoxMenuItem menuItem_viewtoolbar; private javax.swing.JCheckBoxMenuItem menu_bookmarks; private javax.swing.JCheckBoxMenuItem menuitem_aim; private javax.swing.JMenuItem menuitem_deselectall; private javax.swing.JCheckBoxMenuItem menuitem_genomeview; private javax.swing.JMenuItem menuitem_pluginmanager; private javax.swing.JMenuItem menuitem_preferences; private javax.swing.JMenuItem menuitem_redo; private javax.swing.JCheckBoxMenuItem menuitem_ruler; private javax.swing.JCheckBoxMenuItem menuitem_startpage; private javax.swing.JCheckBoxMenuItem menuitem_statusbar; private javax.swing.JCheckBoxMenuItem menuitem_tools; private javax.swing.JMenuItem menuitem_undo; private javax.swing.JCheckBoxMenuItem menuitem_view_plumbline; private javax.swing.JCheckBoxMenuItem menuitem_view_spotlight; private javax.swing.JMenuItem openProjectItem; private javax.swing.JPanel panelExtendedMiddle; private javax.swing.JPanel panel_main; private javax.swing.JPanel panel_toolbar; private javax.swing.JPanel panel_top; private javax.swing.JMenu pluginsMenu; private javax.swing.JMenu recentProjectMenu; private javax.swing.JMenu recentTrackMenu; private javax.swing.JToolBar.Separator s_e_sep; private javax.swing.JMenuItem saveProjectAsItem; private javax.swing.JMenuItem saveProjectItem; private javax.swing.JCheckBoxMenuItem speedAndEfficiencyItem; private javax.swing.JToolBar toolbar_bottom; private javax.swing.JMenuItem tutorialsItem; private javax.swing.JMenuItem userManualItem; private javax.swing.JMenu viewMenu; private javax.swing.ButtonGroup view_buttongroup; private javax.swing.JMenuItem websiteItem; private javax.swing.JMenu windowMenu; // End of variables declaration//GEN-END:variables /** * Customize the UI. This includes doing any platform-specific customization. */ private void customizeUI() { if (MiscUtils.MAC) { try { macOSXApplication = Application.getApplication(); macOSXApplication.setAboutHandler(new AboutHandler() { @Override public void handleAbout(AppEvent.AboutEvent evt) { final Splash dlg = new Splash(instance, true); dlg.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { dlg.setVisible(false); } }); dlg.setVisible(true); } }); macOSXApplication.setPreferencesHandler(new PreferencesHandler() { @Override public void handlePreferences(AppEvent.PreferencesEvent evt) { menuitem_preferencesActionPerformed(null); } }); macOSXApplication.setQuitHandler(new QuitHandler() { @Override public void handleQuitRequestWith(AppEvent.QuitEvent evt, QuitResponse resp) { exitItemActionPerformed(null); // If the user agreed to quit, System.exit would have been // called. Since we got here, the user has said "No" to quitting. resp.cancelQuit(); } }); fileMenu.remove(jSeparator4); fileMenu.remove(exitItem); editMenu.remove(jSeparator7); editMenu.remove(menuitem_preferences); } catch (Throwable x) { LOG.error("Unable to load Apple eAWT classes.", x); DialogUtils.displayError("Warning", "Savant requires Java for Mac OS X 10.6 Update 3 (or later).\nPlease check Software Update for the latest version."); } } LookAndFeelFactory.UIDefaultsCustomizer uiDefaultsCustomizer = new LookAndFeelFactory.UIDefaultsCustomizer() { @Override public void customize(UIDefaults defaults) { ThemePainter painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter"); defaults.put("OptionPaneUI", "com.jidesoft.plaf.basic.BasicJideOptionPaneUI"); defaults.put("OptionPane.showBanner", Boolean.TRUE); // show banner or not. default is true //defaults.put("OptionPane.bannerIcon", JideIconsFactory.getImageIcon(JideIconsFactory.JIDE50)); defaults.put("OptionPane.bannerFontSize", 13); defaults.put("OptionPane.bannerFontStyle", Font.BOLD); defaults.put("OptionPane.bannerMaxCharsPerLine", 60); defaults.put("OptionPane.bannerForeground", Color.BLACK); //painter != null ? painter.getOptionPaneBannerForeground() : null); // you should adjust this if banner background is not the default gradient paint defaults.put("OptionPane.bannerBorder", null); // use default border // set both bannerBackgroundDk and // set both bannerBackgroundLt to null if you don't want gradient //defaults.put("OptionPane.bannerBackgroundDk", painter != null ? painter.getOptionPaneBannerDk() : null); //defaults.put("OptionPane.bannerBackgroundLt", painter != null ? painter.getOptionPaneBannerLt() : null); //defaults.put("OptionPane.bannerBackgroundDirection", Boolean.TRUE); // default is true // optionally, you can set a Paint object for BannerPanel. If so, the three UIDefaults related to banner background above will be ignored. defaults.put("OptionPane.bannerBackgroundPaint", null); defaults.put("OptionPane.buttonAreaBorder", BorderFactory.createEmptyBorder(6, 6, 6, 6)); defaults.put("OptionPane.buttonOrientation", SwingConstants.RIGHT); } }; uiDefaultsCustomizer.customize(UIManager.getDefaults()); } /** * Initialize the Browser */ private void init() { ReferenceController.getInstance().addReferenceChangedListener(this); initGUIFrame(); initDocking(); //initToolsPanel(); initMenu(); initStatusBar(); initBookmarksPanel(); initDataSources(); initStartPage(); dff = new DataFormatForm(this, false); //urlDialog = new OpenURLDialog(this, true); } private void disableExperimentalFeatures() { menuitem_tools.setVisible(false); } public DockingManager getAuxDockingManager() { return auxDockingManager; } public DockingManager getTrackDockingManager() { return trackDockingManager; } private void initToolsPanel() { String frameTitle = "Tools"; DockableFrame df = DockableFrameFactory.createFrame(frameTitle, DockContext.STATE_HIDDEN, DockContext.DOCK_SIDE_SOUTH); df.setAvailableButtons(DockableFrame.BUTTON_AUTOHIDE | DockableFrame.BUTTON_FLOATING | DockableFrame.BUTTON_MAXIMIZE); this.getAuxDockingManager().addFrame(df); MiscUtils.setFrameVisibility(frameTitle, false, this.getAuxDockingManager()); JPanel canvas = new JPanel(); savantTools = new ToolsModule(canvas); // make sure only one active frame //DockingManagerGroup dmg = getDockingManagerGroup(); //new DockingManagerGroup(); //dmg.add(auxDockingManager); //dmg.add(trackDockingManager); df.getContentPane().setLayout(new BorderLayout()); df.getContentPane().add(canvas, BorderLayout.CENTER); } private static DockingManagerGroup dmg; public static void addDockingManagerToGroup(DockingManager m) { if (dmg == null) { dmg = new DockingManagerGroup(); } dmg.add(m); } private void initBookmarksPanel() { DockableFrame df = DockableFrameFactory.createFrame("Bookmarks", DockContext.STATE_HIDDEN, DockContext.DOCK_SIDE_EAST); df.setAvailableButtons(DockableFrame.BUTTON_AUTOHIDE | DockableFrame.BUTTON_FLOATING | DockableFrame.BUTTON_MAXIMIZE); this.getAuxDockingManager().addFrame(df); MiscUtils.setFrameVisibility("Bookmarks", false, this.getAuxDockingManager()); df.getContentPane().setLayout(new BorderLayout()); //JPanel tablePanel = createTabPanel(jtp, "Bookmarks"); favoriteSheet = new BookmarkSheet(this, df.getContentPane()); favoriteController.addFavoritesChangedListener(favoriteSheet); favoriteController.addFavoritesChangedListener(this); } /** * Provide access to the tabbed pane in the bottom auxiliary panel * @return the auxiliary tabbed pane */ public JTabbedPane getAuxTabbedPane() { return auxTabbedPane; } private void askToDispose() { try { ProjectController projectController = ProjectController.getInstance(); if (!projectController.isProjectSaved()) { int answer = DialogUtils.askYesNoCancel("Save project before quitting?"); if (answer == JOptionPane.CANCEL_OPTION) { return; } if (answer == JOptionPane.YES_OPTION) { if (!projectController.promptUserToSaveSession()) { return; } } } //cleanUpBeforeExit(); System.exit(0); } catch (Exception x) { DialogUtils.displayException("Error", "Unable to save project file.", x); } } /** * Set up frame */ void initGUIFrame() { // ask before quitting this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { askToDispose(); } }); // other this.setIconImage( SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.LOGO).getImage()); this.setTitle("Savant Genome Browser"); this.setName("Savant Genome Browser"); } private void initMenu() { loadGenomeItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, osSpecificModifier)); loadFromFileItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, osSpecificModifier)); loadFromURLItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, osSpecificModifier)); loadFromDataSourcePlugin.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, osSpecificModifier)); openProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, osSpecificModifier)); saveProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, osSpecificModifier)); saveProjectAsItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, osSpecificModifier | java.awt.event.InputEvent.SHIFT_MASK)); formatItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, osSpecificModifier)); exitItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, osSpecificModifier)); menuitem_undo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, osSpecificModifier)); menuitem_redo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, osSpecificModifier)); menuItemAddToFaves.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, osSpecificModifier)); menuItem_viewRangeControls.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.SHIFT_MASK | osSpecificModifier)); menuItemPanLeft.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanRight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomIn.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomOut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, java.awt.event.InputEvent.SHIFT_MASK)); menuItemShiftStart.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, java.awt.event.InputEvent.SHIFT_MASK)); menuItemShiftEnd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_END, java.awt.event.InputEvent.SHIFT_MASK)); menuitem_preferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, osSpecificModifier)); menuitem_aim.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, osSpecificModifier)); menuitem_view_plumbline.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, osSpecificModifier)); menuitem_view_spotlight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, osSpecificModifier)); menu_bookmarks.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, osSpecificModifier | java.awt.event.InputEvent.SHIFT_MASK)); menuitem_genomeview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, osSpecificModifier | java.awt.event.InputEvent.SHIFT_MASK)); menuitem_ruler.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, osSpecificModifier | java.awt.event.InputEvent.SHIFT_MASK)); menuitem_statusbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, osSpecificModifier | java.awt.event.InputEvent.SHIFT_MASK)); menuItem_viewtoolbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, osSpecificModifier | java.awt.event.InputEvent.SHIFT_MASK)); exportItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, osSpecificModifier)); if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { tutorialsItem.setEnabled(false); userManualItem.setEnabled(false); websiteItem.setEnabled(false); } initBrowseMenu(); try { RecentTracksController.getInstance().populateMenu(recentTrackMenu); RecentProjectsController.getInstance().populateMenu(recentProjectMenu); } catch (IOException ex) { LOG.error("Unable to populate Recent Items menu.", ex); } } private void initBrowseMenu() { navigationBar = new NavigationBar(); panelExtendedMiddle.setLayout(new BorderLayout()); panelExtendedMiddle.add(navigationBar); navigationBar.setVisible(false); panel_top.setVisible(false); } /** * Prompt the user to open a genome file. * * Expects a Binary Fasta file (created using the data formatter included in * the distribution). */ public void showOpenGenomeDialog() { LoadGenomeDialog d = new LoadGenomeDialog(this,true); d.setVisible(true); } /** * The user has tried to open an unformatted file. Prompt them to format it. * * @param uri the file URI which the user has tried to open. */ public void promptUserToFormatFile(URI uri) { String title = "Unrecognized file: " + uri; String scheme = uri.getScheme(); if (scheme == null || scheme.equals("file")) { int reply = JOptionPane.showConfirmDialog(this, "This file does not appear to be formatted. Format now?", title, JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { if (!dff.isVisible()) { dff.clear(); dff.setInFile(new File(uri)); dff.setLocationRelativeTo(this); dff.setVisible(true); } } } else { // TODO: Do something intelligent for network URIs. JOptionPane.showMessageDialog(this, "This file does not appear to be formatted. Please try to format it."); } } private void showBrowserControls() { if (browserControlsShown) { return; } this.panel_top.setVisible(true); this.menuItem_viewRangeControls.setSelected(true); this.rangeSelector.setVisible(true); this.referenceCombo.setVisible(true); this.menuitem_genomeview.setSelected(true); this.ruler.setVisible(true); this.menuitem_ruler.setSelected(true); this.loadFromFileItem.setEnabled(true); this.loadFromURLItem.setEnabled(true); this.loadFromDataSourcePlugin.setEnabled(true); //setStartPageVisible(false); navigationBar.setVisible(true); browserControlsShown = true; } private void setStartPageVisible(boolean b) { MiscUtils.setFrameVisibility("Start Page", b, this.getTrackDockingManager()); this.menuitem_startpage.setSelected(b); } public void updateStatus(String msg) { this.label_status.setText(msg); this.label_status.revalidate(); } private void initStatusBar() { toolbar_bottom.add(Box.createGlue(), 2); memorystatusbar = new MemoryStatusBarItem(); memorystatusbar.setMaximumSize(new Dimension(100, 30)); memorystatusbar.setFillColor(Color.lightGray); this.toolbar_bottom.add(memorystatusbar); setSpeedAndEfficiencyIndicatorsVisible(false); } @Override public void bookmarksChanged(BookmarksChangedEvent event) { if (!showBookmarksChangedDialog) { return; } //Custom button text Object[] options = {"OK", "Don't show again"}; int n = JOptionPane.showOptionDialog(Savant.getInstance(), event.isAdded() ? "Bookmark added at " + event.getBookmark().getReference() + ":" + event.getBookmark().getRange() : "Bookmark removed at " + event.getBookmark().getRange(), "Bookmarks changed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (n == 1) { showBookmarksChangedDialog = false; } //JOptionPane.showMessageDialog(this, , , JOptionPane.INFORMATION_MESSAGE); } private void addTrackFrame(savant.view.swing.Frame frame) { if (startpage != null && startpage.isVisible()) { startpage.setVisible(false); } // remove bogus "#Workspace" frame List<FrameHandle> simpleFrames = getCleanedOrderedFrames(trackDockingManager); // the number of frames, currently int numframes = simpleFrames.size(); trackDockingManager.addFrame(frame); // move the frame to the bottom of the stack if (numframes != 0) { FrameHandle lastFrame = simpleFrames.get(0); trackDockingManager.moveFrame(frame.getKey(), lastFrame.getKey(),DockContext.DOCK_SIDE_SOUTH); } } private List<FrameHandle> getCleanedOrderedFrames(DockingManager dm) { List<FrameHandle> cleanFrames = new ArrayList<FrameHandle>(); for (FrameHandle h : dm.getOrderedFrames()) { if (!h.getKey().startsWith("#")) { cleanFrames.add(h); } } return cleanFrames; } @Override public void genomeChanged(GenomeChangedEvent event) { LOG.info("Genome changed from " + event.getOldGenome() + " to " + event.getNewGenome()); loadGenomeItem.setText("Change genome..."); showBrowserControls(); } @Override public void referenceChanged(ReferenceChangedEvent event) { Genome loadedGenome = ReferenceController.getInstance().getGenome(); rangeController.setMaxRange(new Range(1, loadedGenome.getLength())); rangeSelector.setMaximum(loadedGenome.getLength()); rangeController.setRange(1, Math.min(1000, loadedGenome.getLength())); } @Override public void handleEvent(ProjectEvent event) { String activity; switch (event.getType()) { case LOADING: activity = "Loading " + event.getPath() + "..."; setTitle("Savant Genome Browser - " + activity); break; case LOADED: case SAVED: MiscUtils.setUnsavedTitle(this, "Savant Genome Browser - " + event.getPath(), false); break; case SAVING: activity = "Saving " + event.getPath() + "..."; setTitle("Savant Genome Browser - " + activity); break; case UNSAVED: MiscUtils.setUnsavedTitle(this, "Savant Genome Browser - " + event.getPath(), true); break; } } private void setSpeedAndEfficiencyIndicatorsVisible(boolean b) { this.speedAndEfficiencyItem.setSelected(b); this.jLabel1.setVisible(b); this.label_memory.setVisible(b); this.label_status.setVisible(b); this.s_e_sep.setVisible(b); this.memorystatusbar.setVisible(b); } public void addPluginToMenu(JCheckBoxMenuItem cb) { pluginsMenu.add(cb); } /* private void cleanUpBeforeExit() { removeTmpFiles(); } */ public void removeTmpFiles() { for (File f : DirectorySettings.getTmpDirectory().listFiles()) { f.delete(); } } private void makeGUIVisible() { setExtendedState(MAXIMIZED_BOTH); setVisible(true); } private void initDataSources() { DataSourcePluginController.getInstance().addDataSourcePlugin(new SavantFileRepositoryDataSourcePlugin()); if (!turnExperimentalFeaturesOff) { DataSourcePluginController.getInstance().addDataSourcePlugin(new SAFEDataSourcePlugin()); } } public void updateMousePosition() { GraphPaneController gpc = GraphPaneController.getInstance(); int x = gpc.getMouseXPosition(); int y = gpc.getMouseYPosition(); if (x == -1 && y == -1) { this.label_mouseposition.setText("mouse not over track"); } else { this.label_mouseposition.setText(((x == -1) ? "" : "X: " + MiscUtils.numToString(x)) + ((y == -1) ? "" : " Y: " + MiscUtils.numToString(y))); } } public String[] getSelectedTracks(boolean multiple, String title) { TrackChooser tc = new TrackChooser(Savant.getInstance(), multiple, title); tc.setVisible(true); String[] tracks = tc.getSelectedTracks(); return tracks; } private void displayAuxPanels() { List<String> names = this.getAuxDockingManager().getAllFrameNames(); for (int i = 0; i < names.size(); i++) { MiscUtils.setFrameVisibility(names.get(i), true, this.getAuxDockingManager()); this.getAuxDockingManager().toggleAutohideState(names.get(i)); break; } //MiscUtils.setFrameVisibility("Bookmarks", true, this.getAuxDockingManager()); //this.getAuxDockingManager().toggleAutohideState("Bookmarks"); menu_bookmarks.setState(true); this.getAuxDockingManager().setActive(false); } public SelectionController getSelectionController() { return this.selectionController; } private void initStartPage() { if (BrowserSettings.getShowStartPage()) { /* DockableFrame df = DockableFrameFactory.createFrame("Start Page", DockContext.STATE_FRAMEDOCKED, DockContext.DOCK_SIDE_NORTH); //df.setAvailableButtons(DockableFrame.BUTTON_CLOSE); df.setShowTitleBar(false); JPanel canvas = (JPanel) df.getContentPane(); canvas.setLayout(new BorderLayout()); canvas.add(new StartPanel(), BorderLayout.CENTER); trackDockingManager.addFrame(df); MiscUtils.setFrameVisibility("Start Page", true,trackDockingManager); try { df.setMaximized(true); } catch (PropertyVetoException ex) { Logger.getLogger(Savant.class.getName()).log(Level.SEVERE, null, ex); } //df.getContentPane().setLayout(new BorderLayout()); // //df.getContentPane().add(start,BorderLayout.CENTER); startPageDockableFrame = df; * */ startpage = new StartPanel(); trackBackground.add(startpage, BorderLayout.CENTER); } } public boolean isWebStart(){ return webStart; } public static void installMissingPlugins(List<String> pluginUrls) { String localFile = null; for (String stringUrl: pluginUrls) { try{ URL url = new URL(stringUrl); InputStream is = url.openStream(); FileOutputStream fos=null; StringTokenizer st=new StringTokenizer(url.getFile(), "/"); while (st.hasMoreTokens()){ localFile=st.nextToken(); } String dir; if(localFile.endsWith("SavantCore.jar")){ File dirFile = DirectorySettings.getLibsDirectory(); if(!dirFile.exists()) dirFile.mkdirs(); dir = dirFile.getPath(); } else { dir = DirectorySettings.getPluginsDirectory().getPath(); } localFile = dir + System.getProperty("file.separator") + localFile; fos = new FileOutputStream(localFile); int oneChar, count=0; while ((oneChar=is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); } catch (Exception e){ LOG.error(e); } } } }
true
true
private void initComponents() { view_buttongroup = new javax.swing.ButtonGroup(); panel_top = new javax.swing.JPanel(); panelExtendedMiddle = new javax.swing.JPanel(); panel_main = new javax.swing.JPanel(); toolbar_bottom = new javax.swing.JToolBar(); label_mouseposition_title = new javax.swing.JLabel(); label_mouseposition = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); label_status = new javax.swing.JLabel(); s_e_sep = new javax.swing.JToolBar.Separator(); label_memory = new javax.swing.JLabel(); panel_toolbar = new javax.swing.JPanel(); menuBar_top = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); loadGenomeItem = new javax.swing.JMenuItem(); loadFromFileItem = new javax.swing.JMenuItem(); loadFromURLItem = new javax.swing.JMenuItem(); loadFromDataSourcePlugin = new javax.swing.JMenuItem(); recentTrackMenu = new javax.swing.JMenu(); javax.swing.JPopupMenu.Separator jSeparator1 = new javax.swing.JPopupMenu.Separator(); openProjectItem = new javax.swing.JMenuItem(); recentProjectMenu = new javax.swing.JMenu(); saveProjectItem = new javax.swing.JMenuItem(); saveProjectAsItem = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator2 = new javax.swing.JPopupMenu.Separator(); formatItem = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator3 = new javax.swing.JPopupMenu.Separator(); exportItem = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); exitItem = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); menuitem_undo = new javax.swing.JMenuItem(); menuitem_redo = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator6 = new javax.swing.JPopupMenu.Separator(); menuItemAddToFaves = new javax.swing.JMenuItem(); menuitem_deselectall = new javax.swing.JMenuItem(); jSeparator7 = new javax.swing.JPopupMenu.Separator(); menuitem_preferences = new javax.swing.JMenuItem(); viewMenu = new javax.swing.JMenu(); menuItemPanLeft = new javax.swing.JMenuItem(); menuItemPanRight = new javax.swing.JMenuItem(); menuItemZoomIn = new javax.swing.JMenuItem(); menuItemZoomOut = new javax.swing.JMenuItem(); menuItemShiftStart = new javax.swing.JMenuItem(); menuItemShiftEnd = new javax.swing.JMenuItem(); javax.swing.JSeparator jSeparator8 = new javax.swing.JSeparator(); menuitem_aim = new javax.swing.JCheckBoxMenuItem(); menuitem_view_plumbline = new javax.swing.JCheckBoxMenuItem(); menuitem_view_spotlight = new javax.swing.JCheckBoxMenuItem(); windowMenu = new javax.swing.JMenu(); menuItem_viewRangeControls = new javax.swing.JCheckBoxMenuItem(); menuitem_genomeview = new javax.swing.JCheckBoxMenuItem(); menuitem_ruler = new javax.swing.JCheckBoxMenuItem(); menuItem_viewtoolbar = new javax.swing.JCheckBoxMenuItem(); menuitem_statusbar = new javax.swing.JCheckBoxMenuItem(); speedAndEfficiencyItem = new javax.swing.JCheckBoxMenuItem(); javax.swing.JSeparator jSeparator9 = new javax.swing.JSeparator(); menuitem_startpage = new javax.swing.JCheckBoxMenuItem(); menuitem_tools = new javax.swing.JCheckBoxMenuItem(); menu_bookmarks = new javax.swing.JCheckBoxMenuItem(); pluginsMenu = new javax.swing.JMenu(); menuitem_pluginmanager = new javax.swing.JMenuItem(); jSeparator10 = new javax.swing.JPopupMenu.Separator(); helpMenu = new javax.swing.JMenu(); userManualItem = new javax.swing.JMenuItem(); tutorialsItem = new javax.swing.JMenuItem(); javax.swing.JMenuItem checkForUpdatesItem = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); javax.swing.JSeparator jSeparator11 = new javax.swing.JSeparator(); websiteItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 204)); panel_top.setMaximumSize(new java.awt.Dimension(1000, 30)); panel_top.setMinimumSize(new java.awt.Dimension(0, 0)); panel_top.setPreferredSize(new java.awt.Dimension(0, 30)); panel_top.setLayout(new java.awt.BorderLayout()); panelExtendedMiddle.setBackground(new java.awt.Color(51, 51, 51)); panelExtendedMiddle.setMinimumSize(new java.awt.Dimension(0, 0)); panelExtendedMiddle.setPreferredSize(new java.awt.Dimension(990, 25)); javax.swing.GroupLayout panelExtendedMiddleLayout = new javax.swing.GroupLayout(panelExtendedMiddle); panelExtendedMiddle.setLayout(panelExtendedMiddleLayout); panelExtendedMiddleLayout.setHorizontalGroup( panelExtendedMiddleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panelExtendedMiddleLayout.setVerticalGroup( panelExtendedMiddleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); panel_top.add(panelExtendedMiddle, java.awt.BorderLayout.CENTER); panel_main.setBackground(new java.awt.Color(153, 153, 153)); panel_main.setMaximumSize(new java.awt.Dimension(99999, 99999)); panel_main.setMinimumSize(new java.awt.Dimension(1, 1)); panel_main.setPreferredSize(new java.awt.Dimension(99999, 99999)); javax.swing.GroupLayout panel_mainLayout = new javax.swing.GroupLayout(panel_main); panel_main.setLayout(panel_mainLayout); panel_mainLayout.setHorizontalGroup( panel_mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panel_mainLayout.setVerticalGroup( panel_mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 526, Short.MAX_VALUE) ); toolbar_bottom.setFloatable(false); toolbar_bottom.setAlignmentX(1.0F); label_mouseposition_title.setText(" Position: "); toolbar_bottom.add(label_mouseposition_title); label_mouseposition.setText("mouse over track"); toolbar_bottom.add(label_mouseposition); jLabel1.setText("Time: "); toolbar_bottom.add(jLabel1); label_status.setMaximumSize(new java.awt.Dimension(300, 14)); label_status.setMinimumSize(new java.awt.Dimension(100, 14)); label_status.setPreferredSize(new java.awt.Dimension(100, 14)); toolbar_bottom.add(label_status); toolbar_bottom.add(s_e_sep); label_memory.setText(" Memory: "); toolbar_bottom.add(label_memory); panel_toolbar.setVisible(false); panel_toolbar.setPreferredSize(new java.awt.Dimension(856, 24)); javax.swing.GroupLayout panel_toolbarLayout = new javax.swing.GroupLayout(panel_toolbar); panel_toolbar.setLayout(panel_toolbarLayout); panel_toolbarLayout.setHorizontalGroup( panel_toolbarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panel_toolbarLayout.setVerticalGroup( panel_toolbarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 24, Short.MAX_VALUE) ); fileMenu.setText("File"); loadGenomeItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK)); loadGenomeItem.setText("Load Genome..."); loadGenomeItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadGenomeItemActionPerformed(evt); } }); fileMenu.add(loadGenomeItem); loadFromFileItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); loadFromFileItem.setText("Load Track from File..."); loadFromFileItem.setEnabled(false); loadFromFileItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromFileItemActionPerformed(evt); } }); fileMenu.add(loadFromFileItem); loadFromURLItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_MASK)); loadFromURLItem.setText("Load Track from URL..."); loadFromURLItem.setEnabled(false); loadFromURLItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromURLItemActionPerformed(evt); } }); fileMenu.add(loadFromURLItem); loadFromDataSourcePlugin.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); loadFromDataSourcePlugin.setText("Load Track from Other Datasource..."); loadFromDataSourcePlugin.setEnabled(false); loadFromDataSourcePlugin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromDataSourcePluginActionPerformed(evt); } }); fileMenu.add(loadFromDataSourcePlugin); recentTrackMenu.setText("Load Recent Track"); fileMenu.add(recentTrackMenu); fileMenu.add(jSeparator1); openProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); openProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openProjectItemActionPerformed(evt); } }); fileMenu.add(openProjectItem); recentProjectMenu.setText("Open Recent Project"); fileMenu.add(recentProjectMenu); saveProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); saveProjectItem.setText("Save Project"); saveProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveProjectItemActionPerformed(evt); } }); fileMenu.add(saveProjectItem); saveProjectAsItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveProjectAsItem.setText("Save Project As..."); saveProjectAsItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveProjectAsItemActionPerformed(evt); } }); fileMenu.add(saveProjectAsItem); fileMenu.add(jSeparator2); formatItem.setText("Format Text File..."); formatItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { formatItemActionPerformed(evt); } }); fileMenu.add(formatItem); fileMenu.add(jSeparator3); exportItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK)); exportItem.setText("Export Track Images..."); exportItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_exportActionPerformed(evt); } }); fileMenu.add(exportItem); fileMenu.add(jSeparator4); exitItem.setText("Exit"); exitItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitItemActionPerformed(evt); } }); fileMenu.add(exitItem); menuBar_top.add(fileMenu); editMenu.setText("Edit"); menuitem_undo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK)); menuitem_undo.setText("Undo Range Change"); menuitem_undo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_undoActionPerformed(evt); } }); editMenu.add(menuitem_undo); menuitem_redo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK)); menuitem_redo.setText("Redo Range Change"); menuitem_redo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_redoActionPerformed(evt); } }); editMenu.add(menuitem_redo); editMenu.add(jSeparator6); menuItemAddToFaves.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK)); menuItemAddToFaves.setText("Bookmark"); menuItemAddToFaves.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemAddToFavesActionPerformed(evt); } }); editMenu.add(menuItemAddToFaves); menuitem_deselectall.setText("Deselect All"); menuitem_deselectall.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_deselectActionPerformed(evt); } }); editMenu.add(menuitem_deselectall); editMenu.add(jSeparator7); menuitem_preferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); menuitem_preferences.setText("Preferences"); menuitem_preferences.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_preferencesActionPerformed(evt); } }); editMenu.add(menuitem_preferences); menuBar_top.add(editMenu); viewMenu.setText("View"); menuItemPanLeft.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanLeft.setText("Pan Left"); menuItemPanLeft.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemPanLeftActionPerformed(evt); } }); viewMenu.add(menuItemPanLeft); menuItemPanRight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanRight.setText("Pan Right"); menuItemPanRight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemPanRightActionPerformed(evt); } }); viewMenu.add(menuItemPanRight); menuItemZoomIn.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomIn.setText("Zoom In"); menuItemZoomIn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemZoomInActionPerformed(evt); } }); viewMenu.add(menuItemZoomIn); menuItemZoomOut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomOut.setText("Zoom Out"); menuItemZoomOut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemZoomOutActionPerformed(evt); } }); viewMenu.add(menuItemZoomOut); menuItemShiftStart.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0)); menuItemShiftStart.setText("Shift to Start"); menuItemShiftStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemShiftStartActionPerformed(evt); } }); viewMenu.add(menuItemShiftStart); menuItemShiftEnd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_END, 0)); menuItemShiftEnd.setText("Shift to End"); menuItemShiftEnd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemShiftEndActionPerformed(evt); } }); viewMenu.add(menuItemShiftEnd); viewMenu.add(jSeparator8); menuitem_aim.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, java.awt.event.InputEvent.CTRL_MASK)); menuitem_aim.setText("Crosshair"); menuitem_aim.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_aimActionPerformed(evt); } }); viewMenu.add(menuitem_aim); menuitem_view_plumbline.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK)); menuitem_view_plumbline.setText("Plumbline"); menuitem_view_plumbline.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_view_plumblineActionPerformed(evt); } }); viewMenu.add(menuitem_view_plumbline); menuitem_view_spotlight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK)); menuitem_view_spotlight.setText("Spotlight"); menuitem_view_spotlight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_view_spotlightActionPerformed(evt); } }); viewMenu.add(menuitem_view_spotlight); menuBar_top.add(viewMenu); windowMenu.setText("Window"); windowMenu.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { windowMenuStateChanged(evt); } }); menuItem_viewRangeControls.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuItem_viewRangeControls.setText("Navigation"); menuItem_viewRangeControls.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItem_viewRangeControlsMousePressed(evt); } }); windowMenu.add(menuItem_viewRangeControls); menuitem_genomeview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_genomeview.setText("Genome"); menuitem_genomeview.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_genomeviewActionPerformed(evt); } }); windowMenu.add(menuitem_genomeview); menuitem_ruler.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_ruler.setText("Ruler"); menuitem_ruler.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_rulerActionPerformed(evt); } }); windowMenu.add(menuitem_ruler); menuItem_viewtoolbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuItem_viewtoolbar.setText("Plugin Toolbar"); menuItem_viewtoolbar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItem_viewtoolbarActionPerformed(evt); } }); windowMenu.add(menuItem_viewtoolbar); menuitem_statusbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_statusbar.setSelected(true); menuitem_statusbar.setText("Status Bar"); menuitem_statusbar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_statusbarActionPerformed(evt); } }); windowMenu.add(menuitem_statusbar); speedAndEfficiencyItem.setText("Resources"); speedAndEfficiencyItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { speedAndEfficiencyItemActionPerformed(evt); } }); windowMenu.add(speedAndEfficiencyItem); windowMenu.add(jSeparator9); menuitem_startpage.setSelected(true); menuitem_startpage.setText("Start Page"); menuitem_startpage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_startpageActionPerformed(evt); } }); windowMenu.add(menuitem_startpage); menuitem_tools.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_tools.setText("Tools"); menuitem_tools.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_toolsActionPerformed(evt); } }); windowMenu.add(menuitem_tools); menu_bookmarks.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menu_bookmarks.setText("Bookmarks"); menu_bookmarks.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_bookmarksActionPerformed(evt); } }); windowMenu.add(menu_bookmarks); menuBar_top.add(windowMenu); pluginsMenu.setText("Plugins"); menuitem_pluginmanager.setText("Plugin Manager"); menuitem_pluginmanager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_pluginmanagerActionPerformed(evt); } }); pluginsMenu.add(menuitem_pluginmanager); pluginsMenu.add(jSeparator10); menuBar_top.add(pluginsMenu); helpMenu.setText("Help"); userManualItem.setText("Manuals"); userManualItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { userManualItemActionPerformed(evt); } }); helpMenu.add(userManualItem); tutorialsItem.setText("Video Tutorials"); tutorialsItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tutorialsItemActionPerformed(evt); } }); helpMenu.add(tutorialsItem); checkForUpdatesItem.setText("Check for updates"); checkForUpdatesItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkForUpdatesItemActionPerformed(evt); } }); helpMenu.add(checkForUpdatesItem); jMenuItem2.setText("Report an issue"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); helpMenu.add(jMenuItem2); jMenuItem1.setText("Request a feature"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); helpMenu.add(jMenuItem1); helpMenu.add(jSeparator11); websiteItem.setText("Website"); websiteItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { websiteItemActionPerformed(evt); } }); helpMenu.add(websiteItem); menuBar_top.add(helpMenu); setJMenuBar(menuBar_top); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel_top, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(toolbar_bottom, javax.swing.GroupLayout.DEFAULT_SIZE, 997, Short.MAX_VALUE) .addContainerGap()) .addComponent(panel_toolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) .addComponent(panel_main, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(panel_top, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(panel_toolbar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(panel_main, javax.swing.GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(toolbar_bottom, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { view_buttongroup = new javax.swing.ButtonGroup(); panel_top = new javax.swing.JPanel(); panelExtendedMiddle = new javax.swing.JPanel(); panel_main = new javax.swing.JPanel(); toolbar_bottom = new javax.swing.JToolBar(); label_mouseposition_title = new javax.swing.JLabel(); label_mouseposition = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); label_status = new javax.swing.JLabel(); s_e_sep = new javax.swing.JToolBar.Separator(); label_memory = new javax.swing.JLabel(); panel_toolbar = new javax.swing.JPanel(); menuBar_top = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); loadGenomeItem = new javax.swing.JMenuItem(); loadFromFileItem = new javax.swing.JMenuItem(); loadFromURLItem = new javax.swing.JMenuItem(); loadFromDataSourcePlugin = new javax.swing.JMenuItem(); recentTrackMenu = new javax.swing.JMenu(); javax.swing.JPopupMenu.Separator jSeparator1 = new javax.swing.JPopupMenu.Separator(); openProjectItem = new javax.swing.JMenuItem(); recentProjectMenu = new javax.swing.JMenu(); saveProjectItem = new javax.swing.JMenuItem(); saveProjectAsItem = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator2 = new javax.swing.JPopupMenu.Separator(); formatItem = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator3 = new javax.swing.JPopupMenu.Separator(); exportItem = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); exitItem = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); menuitem_undo = new javax.swing.JMenuItem(); menuitem_redo = new javax.swing.JMenuItem(); javax.swing.JPopupMenu.Separator jSeparator6 = new javax.swing.JPopupMenu.Separator(); menuItemAddToFaves = new javax.swing.JMenuItem(); menuitem_deselectall = new javax.swing.JMenuItem(); jSeparator7 = new javax.swing.JPopupMenu.Separator(); menuitem_preferences = new javax.swing.JMenuItem(); viewMenu = new javax.swing.JMenu(); menuItemPanLeft = new javax.swing.JMenuItem(); menuItemPanRight = new javax.swing.JMenuItem(); menuItemZoomIn = new javax.swing.JMenuItem(); menuItemZoomOut = new javax.swing.JMenuItem(); menuItemShiftStart = new javax.swing.JMenuItem(); menuItemShiftEnd = new javax.swing.JMenuItem(); javax.swing.JSeparator jSeparator8 = new javax.swing.JSeparator(); menuitem_aim = new javax.swing.JCheckBoxMenuItem(); menuitem_view_plumbline = new javax.swing.JCheckBoxMenuItem(); menuitem_view_spotlight = new javax.swing.JCheckBoxMenuItem(); windowMenu = new javax.swing.JMenu(); menuItem_viewRangeControls = new javax.swing.JCheckBoxMenuItem(); menuitem_genomeview = new javax.swing.JCheckBoxMenuItem(); menuitem_ruler = new javax.swing.JCheckBoxMenuItem(); menuItem_viewtoolbar = new javax.swing.JCheckBoxMenuItem(); menuitem_statusbar = new javax.swing.JCheckBoxMenuItem(); speedAndEfficiencyItem = new javax.swing.JCheckBoxMenuItem(); javax.swing.JSeparator jSeparator9 = new javax.swing.JSeparator(); menuitem_startpage = new javax.swing.JCheckBoxMenuItem(); menuitem_tools = new javax.swing.JCheckBoxMenuItem(); menu_bookmarks = new javax.swing.JCheckBoxMenuItem(); pluginsMenu = new javax.swing.JMenu(); menuitem_pluginmanager = new javax.swing.JMenuItem(); jSeparator10 = new javax.swing.JPopupMenu.Separator(); helpMenu = new javax.swing.JMenu(); userManualItem = new javax.swing.JMenuItem(); tutorialsItem = new javax.swing.JMenuItem(); javax.swing.JMenuItem checkForUpdatesItem = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); javax.swing.JSeparator jSeparator11 = new javax.swing.JSeparator(); websiteItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 204)); panel_top.setMaximumSize(new java.awt.Dimension(1000, 30)); panel_top.setMinimumSize(new java.awt.Dimension(0, 0)); panel_top.setPreferredSize(new java.awt.Dimension(0, 30)); panel_top.setLayout(new java.awt.BorderLayout()); panelExtendedMiddle.setBackground(new java.awt.Color(51, 51, 51)); panelExtendedMiddle.setMinimumSize(new java.awt.Dimension(0, 0)); panelExtendedMiddle.setPreferredSize(new java.awt.Dimension(990, 25)); javax.swing.GroupLayout panelExtendedMiddleLayout = new javax.swing.GroupLayout(panelExtendedMiddle); panelExtendedMiddle.setLayout(panelExtendedMiddleLayout); panelExtendedMiddleLayout.setHorizontalGroup( panelExtendedMiddleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panelExtendedMiddleLayout.setVerticalGroup( panelExtendedMiddleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); panel_top.add(panelExtendedMiddle, java.awt.BorderLayout.CENTER); panel_main.setBackground(new java.awt.Color(153, 153, 153)); panel_main.setMaximumSize(new java.awt.Dimension(99999, 99999)); panel_main.setMinimumSize(new java.awt.Dimension(1, 1)); panel_main.setPreferredSize(new java.awt.Dimension(99999, 99999)); javax.swing.GroupLayout panel_mainLayout = new javax.swing.GroupLayout(panel_main); panel_main.setLayout(panel_mainLayout); panel_mainLayout.setHorizontalGroup( panel_mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panel_mainLayout.setVerticalGroup( panel_mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 526, Short.MAX_VALUE) ); toolbar_bottom.setFloatable(false); toolbar_bottom.setAlignmentX(1.0F); label_mouseposition_title.setText(" Position: "); toolbar_bottom.add(label_mouseposition_title); label_mouseposition.setText("mouse over track"); toolbar_bottom.add(label_mouseposition); jLabel1.setText("Time: "); toolbar_bottom.add(jLabel1); label_status.setMaximumSize(new java.awt.Dimension(300, 14)); label_status.setMinimumSize(new java.awt.Dimension(100, 14)); label_status.setPreferredSize(new java.awt.Dimension(100, 14)); toolbar_bottom.add(label_status); toolbar_bottom.add(s_e_sep); label_memory.setText(" Memory: "); toolbar_bottom.add(label_memory); panel_toolbar.setVisible(false); panel_toolbar.setPreferredSize(new java.awt.Dimension(856, 24)); javax.swing.GroupLayout panel_toolbarLayout = new javax.swing.GroupLayout(panel_toolbar); panel_toolbar.setLayout(panel_toolbarLayout); panel_toolbarLayout.setHorizontalGroup( panel_toolbarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1007, Short.MAX_VALUE) ); panel_toolbarLayout.setVerticalGroup( panel_toolbarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 24, Short.MAX_VALUE) ); fileMenu.setText("File"); loadGenomeItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK)); loadGenomeItem.setText("Load Genome..."); loadGenomeItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadGenomeItemActionPerformed(evt); } }); fileMenu.add(loadGenomeItem); loadFromFileItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); loadFromFileItem.setText("Load Track from File..."); loadFromFileItem.setEnabled(false); loadFromFileItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromFileItemActionPerformed(evt); } }); fileMenu.add(loadFromFileItem); loadFromURLItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_MASK)); loadFromURLItem.setText("Load Track from URL..."); loadFromURLItem.setEnabled(false); loadFromURLItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromURLItemActionPerformed(evt); } }); fileMenu.add(loadFromURLItem); loadFromDataSourcePlugin.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); loadFromDataSourcePlugin.setText("Load Track from Other Datasource..."); loadFromDataSourcePlugin.setEnabled(false); loadFromDataSourcePlugin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromDataSourcePluginActionPerformed(evt); } }); fileMenu.add(loadFromDataSourcePlugin); recentTrackMenu.setText("Load Recent Track"); fileMenu.add(recentTrackMenu); fileMenu.add(jSeparator1); openProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); openProjectItem.setText("Open Project..."); openProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openProjectItemActionPerformed(evt); } }); fileMenu.add(openProjectItem); recentProjectMenu.setText("Open Recent Project"); fileMenu.add(recentProjectMenu); saveProjectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); saveProjectItem.setText("Save Project"); saveProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveProjectItemActionPerformed(evt); } }); fileMenu.add(saveProjectItem); saveProjectAsItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveProjectAsItem.setText("Save Project As..."); saveProjectAsItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveProjectAsItemActionPerformed(evt); } }); fileMenu.add(saveProjectAsItem); fileMenu.add(jSeparator2); formatItem.setText("Format Text File..."); formatItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { formatItemActionPerformed(evt); } }); fileMenu.add(formatItem); fileMenu.add(jSeparator3); exportItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK)); exportItem.setText("Export Track Images..."); exportItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_exportActionPerformed(evt); } }); fileMenu.add(exportItem); fileMenu.add(jSeparator4); exitItem.setText("Exit"); exitItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitItemActionPerformed(evt); } }); fileMenu.add(exitItem); menuBar_top.add(fileMenu); editMenu.setText("Edit"); menuitem_undo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK)); menuitem_undo.setText("Undo Range Change"); menuitem_undo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_undoActionPerformed(evt); } }); editMenu.add(menuitem_undo); menuitem_redo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK)); menuitem_redo.setText("Redo Range Change"); menuitem_redo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_redoActionPerformed(evt); } }); editMenu.add(menuitem_redo); editMenu.add(jSeparator6); menuItemAddToFaves.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK)); menuItemAddToFaves.setText("Bookmark"); menuItemAddToFaves.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemAddToFavesActionPerformed(evt); } }); editMenu.add(menuItemAddToFaves); menuitem_deselectall.setText("Deselect All"); menuitem_deselectall.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_deselectActionPerformed(evt); } }); editMenu.add(menuitem_deselectall); editMenu.add(jSeparator7); menuitem_preferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); menuitem_preferences.setText("Preferences"); menuitem_preferences.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_preferencesActionPerformed(evt); } }); editMenu.add(menuitem_preferences); menuBar_top.add(editMenu); viewMenu.setText("View"); menuItemPanLeft.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanLeft.setText("Pan Left"); menuItemPanLeft.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemPanLeftActionPerformed(evt); } }); viewMenu.add(menuItemPanLeft); menuItemPanRight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, java.awt.event.InputEvent.SHIFT_MASK)); menuItemPanRight.setText("Pan Right"); menuItemPanRight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemPanRightActionPerformed(evt); } }); viewMenu.add(menuItemPanRight); menuItemZoomIn.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomIn.setText("Zoom In"); menuItemZoomIn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemZoomInActionPerformed(evt); } }); viewMenu.add(menuItemZoomIn); menuItemZoomOut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, java.awt.event.InputEvent.SHIFT_MASK)); menuItemZoomOut.setText("Zoom Out"); menuItemZoomOut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemZoomOutActionPerformed(evt); } }); viewMenu.add(menuItemZoomOut); menuItemShiftStart.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0)); menuItemShiftStart.setText("Shift to Start"); menuItemShiftStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemShiftStartActionPerformed(evt); } }); viewMenu.add(menuItemShiftStart); menuItemShiftEnd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_END, 0)); menuItemShiftEnd.setText("Shift to End"); menuItemShiftEnd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItemShiftEndActionPerformed(evt); } }); viewMenu.add(menuItemShiftEnd); viewMenu.add(jSeparator8); menuitem_aim.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, java.awt.event.InputEvent.CTRL_MASK)); menuitem_aim.setText("Crosshair"); menuitem_aim.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_aimActionPerformed(evt); } }); viewMenu.add(menuitem_aim); menuitem_view_plumbline.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK)); menuitem_view_plumbline.setText("Plumbline"); menuitem_view_plumbline.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_view_plumblineActionPerformed(evt); } }); viewMenu.add(menuitem_view_plumbline); menuitem_view_spotlight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK)); menuitem_view_spotlight.setText("Spotlight"); menuitem_view_spotlight.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_view_spotlightActionPerformed(evt); } }); viewMenu.add(menuitem_view_spotlight); menuBar_top.add(viewMenu); windowMenu.setText("Window"); windowMenu.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { windowMenuStateChanged(evt); } }); menuItem_viewRangeControls.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuItem_viewRangeControls.setText("Navigation"); menuItem_viewRangeControls.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItem_viewRangeControlsMousePressed(evt); } }); windowMenu.add(menuItem_viewRangeControls); menuitem_genomeview.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_genomeview.setText("Genome"); menuitem_genomeview.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_genomeviewActionPerformed(evt); } }); windowMenu.add(menuitem_genomeview); menuitem_ruler.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_ruler.setText("Ruler"); menuitem_ruler.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_rulerActionPerformed(evt); } }); windowMenu.add(menuitem_ruler); menuItem_viewtoolbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuItem_viewtoolbar.setText("Plugin Toolbar"); menuItem_viewtoolbar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuItem_viewtoolbarActionPerformed(evt); } }); windowMenu.add(menuItem_viewtoolbar); menuitem_statusbar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_statusbar.setSelected(true); menuitem_statusbar.setText("Status Bar"); menuitem_statusbar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_statusbarActionPerformed(evt); } }); windowMenu.add(menuitem_statusbar); speedAndEfficiencyItem.setText("Resources"); speedAndEfficiencyItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { speedAndEfficiencyItemActionPerformed(evt); } }); windowMenu.add(speedAndEfficiencyItem); windowMenu.add(jSeparator9); menuitem_startpage.setSelected(true); menuitem_startpage.setText("Start Page"); menuitem_startpage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_startpageActionPerformed(evt); } }); windowMenu.add(menuitem_startpage); menuitem_tools.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menuitem_tools.setText("Tools"); menuitem_tools.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_toolsActionPerformed(evt); } }); windowMenu.add(menuitem_tools); menu_bookmarks.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); menu_bookmarks.setText("Bookmarks"); menu_bookmarks.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_bookmarksActionPerformed(evt); } }); windowMenu.add(menu_bookmarks); menuBar_top.add(windowMenu); pluginsMenu.setText("Plugins"); menuitem_pluginmanager.setText("Plugin Manager"); menuitem_pluginmanager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuitem_pluginmanagerActionPerformed(evt); } }); pluginsMenu.add(menuitem_pluginmanager); pluginsMenu.add(jSeparator10); menuBar_top.add(pluginsMenu); helpMenu.setText("Help"); userManualItem.setText("Manuals"); userManualItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { userManualItemActionPerformed(evt); } }); helpMenu.add(userManualItem); tutorialsItem.setText("Video Tutorials"); tutorialsItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tutorialsItemActionPerformed(evt); } }); helpMenu.add(tutorialsItem); checkForUpdatesItem.setText("Check for updates"); checkForUpdatesItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkForUpdatesItemActionPerformed(evt); } }); helpMenu.add(checkForUpdatesItem); jMenuItem2.setText("Report an issue"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); helpMenu.add(jMenuItem2); jMenuItem1.setText("Request a feature"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); helpMenu.add(jMenuItem1); helpMenu.add(jSeparator11); websiteItem.setText("Website"); websiteItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { websiteItemActionPerformed(evt); } }); helpMenu.add(websiteItem); menuBar_top.add(helpMenu); setJMenuBar(menuBar_top); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel_top, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(toolbar_bottom, javax.swing.GroupLayout.DEFAULT_SIZE, 997, Short.MAX_VALUE) .addContainerGap()) .addComponent(panel_toolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) .addComponent(panel_main, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1007, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(panel_top, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(panel_toolbar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(panel_main, javax.swing.GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(toolbar_bottom, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/EclipseConnector.java b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/EclipseConnector.java index 12f9aee6c..ef290abfe 100644 --- a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/EclipseConnector.java +++ b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/EclipseConnector.java @@ -1,260 +1,261 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.help.internal.webapp.servlet; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.UndeclaredThrowableException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.Locale; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.help.internal.base.BaseHelpSystem; import org.eclipse.help.internal.protocols.HelpURLConnection; import org.eclipse.help.internal.protocols.HelpURLStreamHandler; import org.eclipse.help.internal.webapp.HelpWebappPlugin; import org.eclipse.help.internal.webapp.data.ServletResources; import org.eclipse.help.internal.webapp.data.UrlUtil; /** * Performs transfer of data from eclipse to a jsp/servlet */ public class EclipseConnector { private static final String errorPageBegin = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" //$NON-NLS-1$ + "<html><head>\n" //$NON-NLS-1$ + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" //$NON-NLS-1$ + "</head>\n" //$NON-NLS-1$ + "<body><p>\n"; //$NON-NLS-1$ private static final String errorPageEnd = "</p></body></html>"; //$NON-NLS-1$ private static final IFilter filters[] = new IFilter[]{ new HighlightFilter(), new FramesetFilter(), new InjectionFilter(), new DynamicXHTMLFilter(), new BreadcrumbsFilter() }; public EclipseConnector(ServletContext context) { } public void transfer(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { String url = getURL(req); if (url == null) return; // Redirect if the request includes PLUGINS_ROOT and is not a content request int index = url.lastIndexOf(HelpURLConnection.PLUGINS_ROOT); if (index!= -1 && url.indexOf("content/" + HelpURLConnection.PLUGINS_ROOT) == -1) { //$NON-NLS-1$ StringBuffer redirectURL = new StringBuffer(); redirectURL.append(req.getContextPath()); redirectURL.append(req.getServletPath()); redirectURL.append("/"); //$NON-NLS-1$ redirectURL.append(url.substring(index+HelpURLConnection.PLUGINS_ROOT.length())); resp.sendRedirect(redirectURL.toString()); return; } if (url.toLowerCase(Locale.ENGLISH).startsWith("file:") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).startsWith("jar:") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).startsWith("platform:")) { //$NON-NLS-1$ int i = url.indexOf('?'); if (i != -1) url = url.substring(0, i); // ensure the file is only accessed from a local installation if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_INFOCENTER || !UrlUtil.isLocalRequest(req)) { return; } } else { // enable activities matching url // HelpBasePlugin.getActivitySupport().enableActivities(url); url = "help:" + url; //$NON-NLS-1$ } URLConnection con = openConnection(url, req, resp); resp.setContentType(con.getContentType()); long maxAge = 0; try { // getExpiration() throws NullPointerException when URL is // jar:file:... long expiration = con.getExpiration(); maxAge = (expiration - System.currentTimeMillis()) / 1000; if (maxAge < 0) maxAge = 0; } catch (Exception e) { } resp.setHeader("Cache-Control", "max-age=" + maxAge); //$NON-NLS-1$ //$NON-NLS-2$ InputStream is; try { is = con.getInputStream(); } catch (IOException ioe) { + resp.setStatus(HttpServletResponse.SC_NOT_FOUND); if (url.toLowerCase(Locale.ENGLISH).endsWith("htm") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).endsWith("html")) { //$NON-NLS-1$ String error = errorPageBegin + ServletResources.getString("noTopic", req) //$NON-NLS-1$ + errorPageEnd; is = new ByteArrayInputStream(error.getBytes("UTF8")); //$NON-NLS-1$ } else { return; } } catch (Exception e) { // if it's a wrapped exception, unwrap it Throwable t = e; if (t instanceof UndeclaredThrowableException && t.getCause() != null) { t = t.getCause(); } StringBuffer message = new StringBuffer(); message.append(errorPageBegin); message.append("<p>"); //$NON-NLS-1$ message.append(ServletResources.getString( "contentProducerException", //$NON-NLS-1$ req)); message.append("</p>"); //$NON-NLS-1$ message.append("<pre>"); //$NON-NLS-1$ Writer writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); message.append(writer.toString()); message.append("</pre>"); //$NON-NLS-1$ message.append(errorPageEnd); is = new ByteArrayInputStream(message.toString().getBytes("UTF8")); //$NON-NLS-1$ } OutputStream out = resp.getOutputStream(); for (int i = 0; i < filters.length; i++) { out = filters[i].filter(req, out); } transferContent(is, out); out.close(); is.close(); } catch (Exception e) { String msg = "Error processing help request " + getURL(req); //$NON-NLS-1$ HelpWebappPlugin.logError(msg, e); } } /** * Write the body to the response */ private void transferContent(InputStream inputStream, OutputStream out) throws IOException { try { // Prepare the input stream for reading BufferedInputStream dataStream = new BufferedInputStream( inputStream); // Create a fixed sized buffer for reading. // We could create one with the size of availabe data... byte[] buffer = new byte[4096]; int len = 0; while (true) { len = dataStream.read(buffer); // Read file into the byte array if (len == -1) break; out.write(buffer, 0, len); } } catch (Exception e) { } } /** * Gets content from the named url (this could be and eclipse defined url) */ private URLConnection openConnection(String url, HttpServletRequest request, HttpServletResponse response) throws Exception { URLConnection con = null; if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_INFOCENTER) { // it is an infocentre, add client locale to url String locale = UrlUtil.getLocale(request, response); if (url.indexOf('?') >= 0) { url = url + "&lang=" + locale; //$NON-NLS-1$ } else { url = url + "?lang=" + locale; //$NON-NLS-1$ } } URL helpURL; if (url.startsWith("help:")) { //$NON-NLS-1$ helpURL = new URL("help", //$NON-NLS-1$ null, -1, url.substring("help:".length()), //$NON-NLS-1$ HelpURLStreamHandler.getDefault()); } else { if (url.startsWith("jar:")) { //$NON-NLS-1$ // fix for bug 83929 int excl = url.indexOf("!/"); //$NON-NLS-1$ String jar = url.substring(0, excl); String path = url.length() > excl + 2 ? url.substring(excl + 2) : ""; //$NON-NLS-1$ url = jar.replaceAll("!", "%21") + "!/" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + path.replaceAll("!", "%21"); //$NON-NLS-1$ //$NON-NLS-2$ } helpURL = new URL(url); } String protocol = helpURL.getProtocol(); if (!("help".equals(protocol) //$NON-NLS-1$ || "file".equals(protocol) //$NON-NLS-1$ || "platform".equals(protocol) //$NON-NLS-1$ || "jar".equals(protocol))) { //$NON-NLS-1$ throw new IOException(); } con = helpURL.openConnection(); con.setAllowUserInteraction(false); con.setDoInput(true); con.connect(); return con; } /** * Extracts the url from a request */ private String getURL(HttpServletRequest req) { String query = ""; //$NON-NLS-1$ boolean firstParam = true; for (Enumeration params = req.getParameterNames(); params .hasMoreElements();) { String param = (String) params.nextElement(); String[] values = req.getParameterValues(param); if (values == null) continue; for (int i = 0; i < values.length; i++) { if (firstParam) { query += "?" + param + "=" + values[i]; //$NON-NLS-1$ //$NON-NLS-2$ firstParam = false; } else query += "&" + param + "=" + values[i]; //$NON-NLS-1$ //$NON-NLS-2$ } } // the request contains the eclipse url help: or search: String url = req.getPathInfo() + query; if (url.startsWith("/")) //$NON-NLS-1$ url = url.substring(1); return url; } }
true
true
public void transfer(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { String url = getURL(req); if (url == null) return; // Redirect if the request includes PLUGINS_ROOT and is not a content request int index = url.lastIndexOf(HelpURLConnection.PLUGINS_ROOT); if (index!= -1 && url.indexOf("content/" + HelpURLConnection.PLUGINS_ROOT) == -1) { //$NON-NLS-1$ StringBuffer redirectURL = new StringBuffer(); redirectURL.append(req.getContextPath()); redirectURL.append(req.getServletPath()); redirectURL.append("/"); //$NON-NLS-1$ redirectURL.append(url.substring(index+HelpURLConnection.PLUGINS_ROOT.length())); resp.sendRedirect(redirectURL.toString()); return; } if (url.toLowerCase(Locale.ENGLISH).startsWith("file:") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).startsWith("jar:") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).startsWith("platform:")) { //$NON-NLS-1$ int i = url.indexOf('?'); if (i != -1) url = url.substring(0, i); // ensure the file is only accessed from a local installation if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_INFOCENTER || !UrlUtil.isLocalRequest(req)) { return; } } else { // enable activities matching url // HelpBasePlugin.getActivitySupport().enableActivities(url); url = "help:" + url; //$NON-NLS-1$ } URLConnection con = openConnection(url, req, resp); resp.setContentType(con.getContentType()); long maxAge = 0; try { // getExpiration() throws NullPointerException when URL is // jar:file:... long expiration = con.getExpiration(); maxAge = (expiration - System.currentTimeMillis()) / 1000; if (maxAge < 0) maxAge = 0; } catch (Exception e) { } resp.setHeader("Cache-Control", "max-age=" + maxAge); //$NON-NLS-1$ //$NON-NLS-2$ InputStream is; try { is = con.getInputStream(); } catch (IOException ioe) { if (url.toLowerCase(Locale.ENGLISH).endsWith("htm") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).endsWith("html")) { //$NON-NLS-1$ String error = errorPageBegin + ServletResources.getString("noTopic", req) //$NON-NLS-1$ + errorPageEnd; is = new ByteArrayInputStream(error.getBytes("UTF8")); //$NON-NLS-1$ } else { return; } } catch (Exception e) { // if it's a wrapped exception, unwrap it Throwable t = e; if (t instanceof UndeclaredThrowableException && t.getCause() != null) { t = t.getCause(); } StringBuffer message = new StringBuffer(); message.append(errorPageBegin); message.append("<p>"); //$NON-NLS-1$ message.append(ServletResources.getString( "contentProducerException", //$NON-NLS-1$ req)); message.append("</p>"); //$NON-NLS-1$ message.append("<pre>"); //$NON-NLS-1$ Writer writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); message.append(writer.toString()); message.append("</pre>"); //$NON-NLS-1$ message.append(errorPageEnd); is = new ByteArrayInputStream(message.toString().getBytes("UTF8")); //$NON-NLS-1$ } OutputStream out = resp.getOutputStream(); for (int i = 0; i < filters.length; i++) { out = filters[i].filter(req, out); } transferContent(is, out); out.close(); is.close(); } catch (Exception e) { String msg = "Error processing help request " + getURL(req); //$NON-NLS-1$ HelpWebappPlugin.logError(msg, e); } }
public void transfer(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { String url = getURL(req); if (url == null) return; // Redirect if the request includes PLUGINS_ROOT and is not a content request int index = url.lastIndexOf(HelpURLConnection.PLUGINS_ROOT); if (index!= -1 && url.indexOf("content/" + HelpURLConnection.PLUGINS_ROOT) == -1) { //$NON-NLS-1$ StringBuffer redirectURL = new StringBuffer(); redirectURL.append(req.getContextPath()); redirectURL.append(req.getServletPath()); redirectURL.append("/"); //$NON-NLS-1$ redirectURL.append(url.substring(index+HelpURLConnection.PLUGINS_ROOT.length())); resp.sendRedirect(redirectURL.toString()); return; } if (url.toLowerCase(Locale.ENGLISH).startsWith("file:") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).startsWith("jar:") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).startsWith("platform:")) { //$NON-NLS-1$ int i = url.indexOf('?'); if (i != -1) url = url.substring(0, i); // ensure the file is only accessed from a local installation if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_INFOCENTER || !UrlUtil.isLocalRequest(req)) { return; } } else { // enable activities matching url // HelpBasePlugin.getActivitySupport().enableActivities(url); url = "help:" + url; //$NON-NLS-1$ } URLConnection con = openConnection(url, req, resp); resp.setContentType(con.getContentType()); long maxAge = 0; try { // getExpiration() throws NullPointerException when URL is // jar:file:... long expiration = con.getExpiration(); maxAge = (expiration - System.currentTimeMillis()) / 1000; if (maxAge < 0) maxAge = 0; } catch (Exception e) { } resp.setHeader("Cache-Control", "max-age=" + maxAge); //$NON-NLS-1$ //$NON-NLS-2$ InputStream is; try { is = con.getInputStream(); } catch (IOException ioe) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); if (url.toLowerCase(Locale.ENGLISH).endsWith("htm") //$NON-NLS-1$ || url.toLowerCase(Locale.ENGLISH).endsWith("html")) { //$NON-NLS-1$ String error = errorPageBegin + ServletResources.getString("noTopic", req) //$NON-NLS-1$ + errorPageEnd; is = new ByteArrayInputStream(error.getBytes("UTF8")); //$NON-NLS-1$ } else { return; } } catch (Exception e) { // if it's a wrapped exception, unwrap it Throwable t = e; if (t instanceof UndeclaredThrowableException && t.getCause() != null) { t = t.getCause(); } StringBuffer message = new StringBuffer(); message.append(errorPageBegin); message.append("<p>"); //$NON-NLS-1$ message.append(ServletResources.getString( "contentProducerException", //$NON-NLS-1$ req)); message.append("</p>"); //$NON-NLS-1$ message.append("<pre>"); //$NON-NLS-1$ Writer writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); message.append(writer.toString()); message.append("</pre>"); //$NON-NLS-1$ message.append(errorPageEnd); is = new ByteArrayInputStream(message.toString().getBytes("UTF8")); //$NON-NLS-1$ } OutputStream out = resp.getOutputStream(); for (int i = 0; i < filters.length; i++) { out = filters[i].filter(req, out); } transferContent(is, out); out.close(); is.close(); } catch (Exception e) { String msg = "Error processing help request " + getURL(req); //$NON-NLS-1$ HelpWebappPlugin.logError(msg, e); } }
diff --git a/src/uk/co/unitycoders/pircbotx/commands/RandCommand.java b/src/uk/co/unitycoders/pircbotx/commands/RandCommand.java index 4c51ad8..a1ff589 100644 --- a/src/uk/co/unitycoders/pircbotx/commands/RandCommand.java +++ b/src/uk/co/unitycoders/pircbotx/commands/RandCommand.java @@ -1,56 +1,56 @@ /** * Copyright © 2012 Bruce Cowan <[email protected]> * * This file is part of uc_PircBotX. * * uc_PircBotX 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. * * uc_PircBotX 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 uc_PircBotX. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.unitycoders.pircbotx.commands; import java.util.ArrayList; import java.util.Random; import org.pircbotx.PircBotX; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.MessageEvent; /** * Keeps a log of all the lines said, and randomly speaks one * * @author Bruce Cowan */ public class RandCommand extends ListenerAdapter<PircBotX> { private ArrayList<String> lines; private Random random; public RandCommand() { this.lines = new ArrayList<String>(); this.random = new Random(); } @Override public void onMessage(MessageEvent<PircBotX> event) throws Exception { String msg = event.getMessage(); - if (msg.startsWith("!time")) + if (msg.startsWith("!rand")) { int size = this.lines.size(); int index = this.random.nextInt(size - 1); event.respond(this.lines.get(index)); } } }
true
true
public void onMessage(MessageEvent<PircBotX> event) throws Exception { String msg = event.getMessage(); if (msg.startsWith("!time")) { int size = this.lines.size(); int index = this.random.nextInt(size - 1); event.respond(this.lines.get(index)); } }
public void onMessage(MessageEvent<PircBotX> event) throws Exception { String msg = event.getMessage(); if (msg.startsWith("!rand")) { int size = this.lines.size(); int index = this.random.nextInt(size - 1); event.respond(this.lines.get(index)); } }
diff --git a/melati/src/main/java/org/melati/test/Regression.java b/melati/src/main/java/org/melati/test/Regression.java index 48c2a464f..466126f24 100644 --- a/melati/src/main/java/org/melati/test/Regression.java +++ b/melati/src/main/java/org/melati/test/Regression.java @@ -1,30 +1,31 @@ package org.melati.test; import org.melati.poem.*; public class Regression { public static final String dbName = "melatiregression"; public static void main(String[] args) throws Exception { - if (Runtime.exec("destroydb " + dbName).waitFor() != 0 || - Runtime.exec("createdb " + dbName).waitFor() != 0) - exit(1); + // ttj remove to allow it to compile +// if (Runtime.exec("destroydb " + dbName).waitFor() != 0 || +// Runtime.exec("createdb " + dbName).waitFor() != 0) +// exit(1); final Database database = new PoemDatabase(); database.connect(new org.melati.poem.postgresql.jdbc2.Driver(), - "jdbc:postgresql:" + melatiregression, "postgres", "*"); + "jdbc:postgresql:" + dbName, "postgres", "*"); // to test: // creation // deletion // attempt to re-create // // rollback // blocking // deadlock recovery } }
false
true
public static void main(String[] args) throws Exception { if (Runtime.exec("destroydb " + dbName).waitFor() != 0 || Runtime.exec("createdb " + dbName).waitFor() != 0) exit(1); final Database database = new PoemDatabase(); database.connect(new org.melati.poem.postgresql.jdbc2.Driver(), "jdbc:postgresql:" + melatiregression, "postgres", "*"); // to test: // creation // deletion // attempt to re-create // // rollback // blocking // deadlock recovery }
public static void main(String[] args) throws Exception { // ttj remove to allow it to compile // if (Runtime.exec("destroydb " + dbName).waitFor() != 0 || // Runtime.exec("createdb " + dbName).waitFor() != 0) // exit(1); final Database database = new PoemDatabase(); database.connect(new org.melati.poem.postgresql.jdbc2.Driver(), "jdbc:postgresql:" + dbName, "postgres", "*"); // to test: // creation // deletion // attempt to re-create // // rollback // blocking // deadlock recovery }
diff --git a/src/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java b/src/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java index 581571c..0aa2a46 100644 --- a/src/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java +++ b/src/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java @@ -1,34 +1,34 @@ package edu.jhu.thrax.hadoop.jobs; import edu.jhu.thrax.hadoop.features.mapred.*; public class FeatureJobFactory { public static MapReduceFeature get(String name) { if (name.equals("e2fphrase")) return new SourcePhraseGivenTargetFeature(); else if (name.equals("f2ephrase")) return new TargetPhraseGivenSourceFeature(); else if (name.equals("rarity")) return new RarityPenaltyFeature(); else if (name.equals("lexprob")) return new LexicalProbabilityFeature(); else if (name.equals("f_given_lhs")) return new SourcePhraseGivenLHSFeature(); else if (name.equals("lhs_given_f")) return new LhsGivenSourcePhraseFeature(); else if (name.equals("f_given_e_and_lhs")) return new SourcePhraseGivenTargetandLHSFeature(); else if (name.equals("e_given_lhs")) return new TargetPhraseGivenLHSFeature(); else if (name.equals("lhs_given_e")) return new LhsGivenTargetPhraseFeature(); else if (name.equals("e_inv_given_lhs")) - return new TargetPhraseGivenLHSFeature(); + return new InvariantTargetPhraseGivenLHSFeature(); else if (name.equals("lhs_given_e_inv")) - return new LhsGivenTargetPhraseFeature(); + return new InvariantLhsGivenTargetPhraseFeature(); else if (name.equals("e_given_f_and_lhs")) return new TargetPhraseGivenSourceandLHSFeature(); return null; } }
false
true
public static MapReduceFeature get(String name) { if (name.equals("e2fphrase")) return new SourcePhraseGivenTargetFeature(); else if (name.equals("f2ephrase")) return new TargetPhraseGivenSourceFeature(); else if (name.equals("rarity")) return new RarityPenaltyFeature(); else if (name.equals("lexprob")) return new LexicalProbabilityFeature(); else if (name.equals("f_given_lhs")) return new SourcePhraseGivenLHSFeature(); else if (name.equals("lhs_given_f")) return new LhsGivenSourcePhraseFeature(); else if (name.equals("f_given_e_and_lhs")) return new SourcePhraseGivenTargetandLHSFeature(); else if (name.equals("e_given_lhs")) return new TargetPhraseGivenLHSFeature(); else if (name.equals("lhs_given_e")) return new LhsGivenTargetPhraseFeature(); else if (name.equals("e_inv_given_lhs")) return new TargetPhraseGivenLHSFeature(); else if (name.equals("lhs_given_e_inv")) return new LhsGivenTargetPhraseFeature(); else if (name.equals("e_given_f_and_lhs")) return new TargetPhraseGivenSourceandLHSFeature(); return null; }
public static MapReduceFeature get(String name) { if (name.equals("e2fphrase")) return new SourcePhraseGivenTargetFeature(); else if (name.equals("f2ephrase")) return new TargetPhraseGivenSourceFeature(); else if (name.equals("rarity")) return new RarityPenaltyFeature(); else if (name.equals("lexprob")) return new LexicalProbabilityFeature(); else if (name.equals("f_given_lhs")) return new SourcePhraseGivenLHSFeature(); else if (name.equals("lhs_given_f")) return new LhsGivenSourcePhraseFeature(); else if (name.equals("f_given_e_and_lhs")) return new SourcePhraseGivenTargetandLHSFeature(); else if (name.equals("e_given_lhs")) return new TargetPhraseGivenLHSFeature(); else if (name.equals("lhs_given_e")) return new LhsGivenTargetPhraseFeature(); else if (name.equals("e_inv_given_lhs")) return new InvariantTargetPhraseGivenLHSFeature(); else if (name.equals("lhs_given_e_inv")) return new InvariantLhsGivenTargetPhraseFeature(); else if (name.equals("e_given_f_and_lhs")) return new TargetPhraseGivenSourceandLHSFeature(); return null; }
diff --git a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java index 941f1166..d8f1638b 100644 --- a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java +++ b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java @@ -1,7916 +1,7916 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Hashtable; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo; import org.sakaiproject.assignment.taggable.api.TaggingManager; import org.sakaiproject.assignment.taggable.api.TaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException; import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.user.api.User; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** Reference to an assignment submission object */ private static final String SUBMISSION_REF = "submissionRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("taggable", Boolean.valueOf(true)); } String template = null; context.put("tlang", rb); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? context.put("allowUpdateSite", Boolean .valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))); // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_LIST_ASSIGNMENTS)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (mode.equals(MODE_LIST_ASSIGNMENTS)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION)) { // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_GRADE)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } return template; } // buildNormalContext /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", (String) state.getAttribute(STATE_CONTEXT_STRING)); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); } User user = (User) state.getAttribute(STATE_USER); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment", currentAssignment); AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING)); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", new Boolean(allowSubmit)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); // get user information User user = (User) state.getAttribute(STATE_USER); context.put("user_name", user.getDisplayName()); context.put("user_id", user.getDisplayId()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment_title", currentAssignment.getTitle()); AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user); if (s != null) { context.put("submission_id", s.getId()); context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getSubmittedAttachments()); } context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", (String) state.getAttribute(STATE_CONTEXT_STRING)); String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); } try { Assignment currentAssignment = AssignmentService.getAssignment(aId); context.put("assignment", currentAssignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("gradeTypeTable", gradeTypeTable()); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { context.put("assignment", AssignmentService.getAssignment(aReference)); context.put("submission", AssignmentService.getSubmission(aReference, user)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); } try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID)); context.put("assignment", s.getAssignment()); context.put("submission", s); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_get_submission")); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("providers", taggingManager.getProviders()); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", (User) state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", new Long(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } List assignments = prepPage(state); context.put("assignments", assignments.iterator()); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = site.getGroups(); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", new Boolean(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("assignment", a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14") + ": " + assignmentId); } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_OpenMonth", NEW_ASSIGNMENT_OPENMONTH); context.put("name_OpenDay", NEW_ASSIGNMENT_OPENDAY); context.put("name_OpenYear", NEW_ASSIGNMENT_OPENYEAR); context.put("name_OpenHour", NEW_ASSIGNMENT_OPENHOUR); context.put("name_OpenMin", NEW_ASSIGNMENT_OPENMIN); context.put("name_OpenAMPM", NEW_ASSIGNMENT_OPENAMPM); context.put("name_DueMonth", NEW_ASSIGNMENT_DUEMONTH); context.put("name_DueDay", NEW_ASSIGNMENT_DUEDAY); context.put("name_DueYear", NEW_ASSIGNMENT_DUEYEAR); context.put("name_DueHour", NEW_ASSIGNMENT_DUEHOUR); context.put("name_DueMin", NEW_ASSIGNMENT_DUEMIN); context.put("name_DueAMPM", NEW_ASSIGNMENT_DUEAMPM); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("name_CloseMonth", NEW_ASSIGNMENT_CLOSEMONTH); context.put("name_CloseDay", NEW_ASSIGNMENT_CLOSEDAY); context.put("name_CloseYear", NEW_ASSIGNMENT_CLOSEYEAR); context.put("name_CloseHour", NEW_ASSIGNMENT_CLOSEHOUR); context.put("name_CloseMin", NEW_ASSIGNMENT_CLOSEMIN); context.put("name_CloseAMPM", NEW_ASSIGNMENT_CLOSEAMPM); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } // gradebook integration context.put("withGradebook", Boolean.valueOf(AssignmentService.isGradebookDefined())); // number of resubmissions allowed context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // set the values context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_OpenMonth", state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)); context.put("value_OpenDay", state.getAttribute(NEW_ASSIGNMENT_OPENDAY)); context.put("value_OpenYear", state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)); context.put("value_OpenHour", state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)); context.put("value_OpenMin", state.getAttribute(NEW_ASSIGNMENT_OPENMIN)); context.put("value_OpenAMPM", state.getAttribute(NEW_ASSIGNMENT_OPENAMPM)); context.put("value_DueMonth", state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); context.put("value_DueDay", state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); context.put("value_DueYear", state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); context.put("value_DueHour", state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); context.put("value_DueMin", state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); context.put("value_DueAMPM", state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_CloseMonth", state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)); context.put("value_CloseDay", state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)); context.put("value_CloseYear", state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)); context.put("value_CloseHour", state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)); context.put("value_CloseMin", state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)); context.put("value_CloseAMPM", state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_totalSubmissionTypes", new Integer(Assignment.SUBMISSION_TYPES.length)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // number of resubmissions allowed if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } else { // defaults to 0 context.put("value_allowResubmitNumber", Integer.valueOf(0)); } // get all available assignments from Gradebook tool except for those created from boolean gradebookExists = AssignmentService.isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); // get all assignments in Gradebook List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new Vector(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); } } context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo); if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (range != null && range.length() != 0) { context.put("range", range); } else { if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc))); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue()) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } } // setAssignmentFormContext /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); Time openTime = getOpenTime(state); context.put("value_OpenDate", openTime); // due time int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); // get all available assignments from Gradebook tool except for those created from if (AssignmentService.isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); context.put("value_assignment_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { Vector assignments = new Vector(); Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < assignmentIds.size(); i++) { try { Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i)); Iterator submissions = AssignmentService.getSubmissions(a); if (submissions.hasNext()) { // if there is submission to the assignment, show the alert addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n"); } assignments.add(a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } context.put("assignments", assignments); context.put("service", AssignmentService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { int gradeType = -1; // assignment Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // assignment submission try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } // get the submission level of close date setting context.put("name_CloseMonth", ALLOW_RESUBMIT_CLOSEMONTH); context.put("name_CloseDay", ALLOW_RESUBMIT_CLOSEDAY); context.put("name_CloseYear", ALLOW_RESUBMIT_CLOSEYEAR); context.put("name_CloseHour", ALLOW_RESUBMIT_CLOSEHOUR); context.put("name_CloseMin", ALLOW_RESUBMIT_CLOSEMIN); context.put("name_CloseAMPM", ALLOW_RESUBMIT_CLOSEAMPM); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); Time time = null; if (closeTimeString != null) { // if there is a local setting time = TimeService.newTime(Long.parseLong(closeTimeString)); } else if (a != null) { // if there is no local setting, default to assignment close time time = a.getCloseTime(); } TimeBreakdown closeTime = time.breakdownLocal(); context.put("value_CloseMonth", new Integer(closeTime.getMonth())); context.put("value_CloseDay", new Integer(closeTime.getDay())); context.put("value_CloseYear", new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { context.put("value_CloseAMPM", "PM"); } else { context.put("value_CloseAMPM", "AM"); } if (closeHour == 0) { // for midnight point, we mark it as 12AM closeHour = 12; } context.put("value_CloseHour", new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); context.put("value_CloseMin", new Integer(closeTime.getMin())); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("gradingAttachments", state.getAttribute(ATTACHMENTS)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // submission try { context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID))); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); context.put("assignment", a); state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); List userSubmissions = prepPage(state); state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); // ever set the default grade for no-submissions String noSubmissionDefaultGrade = a.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (noSubmissionDefaultGrade != null) { context.put("noSubmissionDefaultGrade", noSubmissionDefaultGrade); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("providers", taggingManager.getProviders()); } context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider .getProvider() .getActivityHelperInfo( (String) state.getAttribute(VIEW_ASSIGNMENT_ID)); if (helper != null) { activityHelpers.add(helper); } } context.put("activityHelpers", activityHelpers); context.put("providers", providers); } context.put("tlang", rb); try { context.put("assignment", AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID))); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get the realm and its member List studentMembers = new Vector(); String realmId = SiteService.siteReference((String) state.getAttribute(STATE_CONTEXT_STRING)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); Set allowSubmitMembers = realm.getUsersIsAllowed(AssignmentService.SECURE_ADD_ASSIGNMENT_SUBMISSION); for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } catch (GroupNotDefinedException e) { Log.warn("chef", this + " IdUnusedException, not found, or not an AuthzGroup object"); addAlert(state, rb.getString("java.realm") + realmId); } context.put("studentMembers", studentMembers); context.put("assignmentService", AssignmentService.getInstance()); Hashtable showStudentAssignments = new Hashtable(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); showStudentAssignments.put(user, AssignmentService.getAssignmentsForContext(contextString, userId)); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED); context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT); context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE); add2ndToolbarFields(data, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool("sakai.assignment.grades"); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); try { AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // try } // doView_submission /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // String assignmentId = params.getString(assignmentId); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE)); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the preview edit assignment process */ public void doDone_preview_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the edit assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_edit_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object // resetAssignment (state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId); Assignment a = sEdit.getAssignment(); if (gradeOption.equals("release")) { sEdit.setGradeReleased(true); // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if (gradeOption.equals("return")) { if (StringUtil.trimToNull(grade) != null) { sEdit.setGradeReleased(true); } sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if (gradeOption.equals("return") || gradeOption.equals("release")) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradeReleased(false); } else { if (typeOfGrade == 1) { sEdit.setGrade("no grade"); sEdit.setGraded(true); } else { if (!grade.equals("")) { if (typeOfGrade == 3) { sEdit.setGrade(grade); } else { sEdit.setGrade(grade); } sEdit.setGraded(true); } } } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getAllowSubmitCloseTime(state); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } // the instructor comment String feedbackCommentString = StringUtil .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); AssignmentService.commitEdit(sEdit); // update grades in gradebook String aReference = a.getReference(); String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (associateGradebookAssignment != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { // update grade in gradebook AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update"); } } catch (IdUnusedException e) { } catch (PermissionException e) { } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } // try if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = "false"; } String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); User u = (User) state.getAttribute(STATE_USER); if (state.getAttribute(STATE_MESSAGE) == null) { try { Assignment a = AssignmentService.getAssignment(aReference); String assignmentId = a.getId(); AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u); if (submission != null) { // the submission already exists, change the text and honor pledge value, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first edit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot12")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state .getAttribute(STATE_CONTEXT_STRING), assignmentId); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot4")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // doSave_submission /** * Action is to post the submission */ public void doPost_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = null; try { a = AssignmentService.getAssignment(aReference); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == 1) { // for the inline only submission if (text.length() == 0) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == 2) { // for the attachment only submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == 3) { // for the inline and attachment submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((text.length() == 0) && ((v == null) || (v.size() == 0))) { addAlert(state, rb.getString("youmust2")); } } } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { try { AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u); if (submission != null) { // the submission already exists, change the text and honor pledge value, post it try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(true); // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. if (sEdit.getReturned()) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (sEdit.getGraded()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtil.split(previousGrades, " "); String newGrades = ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(".") == -1) { // show the grade with decimal point grade = grade.concat(".0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } previousGrades = previousGrades.concat(sEdit.getGradeDisplay() + " "); sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGrade(""); sEdit.setGradeReleased(false); } // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = sEdit.getFeedbackText() + "\n" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = sEdit.getFeedbackComment() + "\n" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); for (int k = 0; k<feedbackAttachments.size();k++) { feedbackAttachmentHistory = ((Reference) feedbackAttachments.get(k)).getReference() + "," + feedbackAttachmentHistory; } sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); // decrease the allow_resubmit_number if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } } } // sEdit.addSubmitter (u); sEdit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(sEdit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("no_permissiion_to_edit_submission")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, post it try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(true); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); } } // if -else } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // if } // doPost_submission /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot2")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doNew_Assignment /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); if (title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } // open time int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth)); int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay)); int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear)); int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour)); int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin)); String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); // validate date if (!Validator.checkDate(openDay, openMonth, openYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + "."); } // due time int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth)); int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay)); int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear)); int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour)); int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin)); String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); // validate date if (dueTime.before(TimeService.newTime())) { addAlert(state, rb.getString("assig4")); } if (!Validator.checkDate(dueDay, dueMonth, dueYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + "."); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // close time int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); // validate date if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } if (closeTime.before(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE))); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType)); } // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); // correct inputs // checks on the times if (validify && dueTime.before(openTime)) { addAlert(state, rb.getString("assig3")); } if (validify) { if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of releasing grade, user must specify a grade addAlert(state, rb.getString("plespethe2")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if (range.equals("groups")) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } // allow resubmission numbers String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (nString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } } // setNewAssignmentParameters /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment option */ public void doHide_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option"); } // doHide_assignment_option /** * Action is to show the assignment option */ public void doShow_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); } // doShow_assignment_option /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment postOrSaveAssignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (String key : helperParms.keySet()) { state.setAttribute(key, helperParms.get(key)); } } // doHelp_activity /** * post or save assignment */ private void postOrSaveAssignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && postOrSave.equals("post"); // assignment old title String aOldTitle = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId); // Assignment AssignmentEdit a = getAssignmentEdit(state, assignmentId); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); // open time Time openTime = getOpenTime(state); // due time Time dueTime = getDueTime(state); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getCloseTime(state); } // sections String s = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; // the attachments List attachments = (List) state.getAttribute(ATTACHMENTS); List attachments1 = EntityManager.newReferenceList(attachments); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new Vector(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); groups.add(site.getGroup(groupId)); } } catch (Exception e) { Log.warn("chef", this + "cannot find site with id "+ siteId); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); // old open time Time oldOpenTime = a.getOpenTime(); // old due time Time oldDueTime = a.getDueTime(); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, title, submissionType, gradeType, gradePoints, description, checkAddHonorPledge, attachments1); // in case of non-electronic submission, create submissions for all students and mark it as submitted if (ac.getTypeOfSubmission()== Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String authzGroupId = SiteService.siteReference(contextString); List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(a.getReference()); try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { if (AssignmentService.getSubmission(a.getReference(), u) == null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(contextString, a.getId()); submission.removeSubmitter(UserDirectoryService.getCurrentUser()); submission.addSubmitter(u); submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } } } catch (Exception e) { Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId); } } // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); editAssignmentProperties(a, title, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit); // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, s, range, groups); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); } if (post) { // only if user is posting the assignment // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook integrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range); } // if } // if } // if } // postOrSaveAssignment /** * called from postOrSaveAssignment function to do integration * @param state * @param siteId * @param aOldTitle * @param oAssociateGradebookAssignment * @param a * @param title * @param dueTime * @param gradeType * @param gradePoints * @param addtoGradebook * @param associateGradebookAssignment * @param range */ private void integrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) { String aReference = a.getReference(); if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if grouped assignment is not allowed to add into Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups"))) { addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().removeProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, AssignmentService.GRADEBOOK_INTEGRATION_NO, null, null, -1, null, null, "remove"); } else { if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && gradeType == 3) { try { //integrate assignment with gradebook //add all existing grades, if any, into Gradebook AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, addtoGradebook, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, "update"); // if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment)) { AssignmentService.integrateGradebook(aReference, oAssociateGradebookAssignment, null, null, null, -1, null, null, "remove"); } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); } } else { // otherwise, cannot do the association } } } else { // remove assignment entry from Gradebook AssignmentService.integrateGradebook(aReference, oAssociateGradebookAssignment, AssignmentService.GRADEBOOK_INTEGRATION_NO, null, null, -1, null, null, "remove"); } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { String openDateAnnounced = a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); // open date has been announced or title has been changed? boolean openDateMessageModified = false; if (openDateAnnounced != null && openDateAnnounced.equalsIgnoreCase(Boolean.TRUE.toString())) { if (oldOpenTime != null && (!oldOpenTime.toStringLocalFull().equals(openTime.toStringLocalFull())) // open time changes || !aOldTitle.equals(title)) // assignment title changes { // need to change message openDateMessageModified = true; } } // add the open date to annoucement if (openDateAnnounced == null // no announcement yet || (openDateAnnounced != null && openDateAnnounced.equalsIgnoreCase(Boolean.TRUE.toString()) && openDateMessageModified)) // announced, but open date or announcement title changes { // announcement channel is in place try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getString("assig6") + " " + title); message.setBody(/* body */rb.getString("opedat") + " " + FormattedText.convertPlaintextToFormattedText(title) + rb.getString("is") + openTime.toStringLocalFull() + ". "); } else { // revised announcement header.setSubject(/* subject */rb.getString("assig5") + " " + title); message.setBody(/* body */rb.getString("newope") + " " + FormattedText.convertPlaintextToFormattedText(title) + rb.getString("is") + openTime.toStringLocalFull() + ". "); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new Vector(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log Log.warn("chef", exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, NotificationService.NOTI_NONE); // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotmak")); } } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { if (state.getAttribute(CALENDAR) != null) { Calendar c = (Calendar) state.getAttribute(CALENDAR); String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null && c != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". "); } catch (PermissionException ee) { Log.warn("chef", "You do not have the permission to view the schedule event id= " + oldEventId + "."); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found) { // remove the founded old event try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { if (c != null) { // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new Vector(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); eGroups.add(site.getGroup(groupRef)); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("due") + " " + title, /* description */rb.getString("assig1") + " " + title + " " + "is due on " + dueTime.toStringLocalFull() + ". ", /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */EntityManager.newReferenceList()); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId()); } } catch (IdUnusedException ee) { Log.warn("chef", ee.getMessage()); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotfin1")); } catch (Exception ee) { Log.warn("chef", ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } // if } // if } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setOpenTime(openTime); a.setDueTime(dueTime); // set the drop dead date as the due date a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } // post the assignment a.setDraft(!post); try { if (range.equals("site")) { a.setAccess(Assignment.AssignmentAccess.SITE); a.clearGroupAccess(); } else if (range.equals("groups")) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } } private void editAssignmentProperties(AssignmentEdit a, String title, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, title); } // allow resubmit number if (allowResubmitNumber != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setTypeOfSubmission(submissionType); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); // add each attachment Iterator it = EntityManager.newReferenceList(attachments1).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); // commit the changes AssignmentService.commitEdit(ac); } private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId) { AssignmentEdit a = null; if (assignmentId.length() == 0) { // create a new assignment try { a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } } else { try { // edit assignment a = AssignmentService.editAssignment(assignmentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // try-catch } // if-else return a; } private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot3")); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin4")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot15")); } } return ac; } private Time getOpenTime(SessionState state) { int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue(); int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue(); int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue(); int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue(); int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue(); String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); return openTime; } private Time getCloseTime(SessionState state) { Time closeTime; int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } private Time getDueTime(SessionState state) { int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); return dueTime; } private Time getAllowSubmitCloseTime(SessionState state) { int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { postOrSaveAssignment(data, "save"); } // doSave_assignment /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, false); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); EventTrackingService.post(EventTrackingService.newEvent(AssignmentService.SECURE_ACCESS_ASSIGNMENT, a.getReference(), false)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); Iterator submissions = AssignmentService.getSubmissions(a); if (submissions.hasNext()) { boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted()) { anySubmitted = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum")); } else { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); TimeBreakdown openTime = a.getOpenTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear())); int openHour = openTime.getHour(); if (openHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM"); } if (openHour == 0) { // for midnight point, we mark it as 12AM openHour = 12; } state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin())); TimeBreakdown dueTime = a.getDueTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear())); int dueHour = dueTime.getHour(); if (dueHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM"); } if (dueHour == 0) { // for midnight point, we mark it as 12AM dueHour = 12; } state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin())); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); TimeBreakdown closeTime = a.getCloseTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM"); } if (closeHour == 0) { // for the midnight point, we mark it as 12 AM closeHour = 12; } state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin())); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission())); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doEdit_Assignment /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { Vector ids = new Vector(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getString("youarenot9") + " " + id + ". "); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); try { AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove releted event if there is one String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { removeCalendarEvent(state, aEdit, pEdit, title); } // if-else if (!AssignmentService.getSubmissions(aEdit).hasNext()) { // there is no submission to this assignment yet, delete the assignment record completely try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(aEdit); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // remove the assignment by marking the remove status property true pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString()); AssignmentService.commitEdit(aEdit); } // remove from Gradebook AssignmentService.integrateGradebook((String) ids.get (i), associateGradebookAssignment, AssignmentService.GRADEBOOK_INTEGRATION_NO, null, null, -1, null, null, "remove"); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot6")); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDelete_Assignment private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException { // remove the associated calender event Calendar c = (Calendar) state.getAttribute(CALENDAR); if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition } catch (PermissionException ee) { } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } // remove the founded old event if (found) { // found the old event delete it try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); try { AssignmentEdit a = AssignmentService.editAssignment(currentId); try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(a); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". "); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); } catch (IdInvalidException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval")); } catch (IdUnusedException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee")); } catch (Exception e) { } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); // reset the grade assignment id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId")); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId")); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if ((s.getFeedbackText() != null) && (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); ResourceProperties p = s.getProperties(); if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null) { // if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property allowResubmitNumber = "1"; } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doGrade_submission /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); try { // get the assignment Assignment a = AssignmentService.getAssignment(params.getString("assignmentId")); String aReference = a.getReference(); Iterator submissions = AssignmentService.getSubmissions(a); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded()) { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !grade.equals("")) { sEdit.setGradeReleased(true); } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, null, a.getTitle(), a.getTitle(), -1, null, null, "update"); // set the gradebook assignment to be released to student AssignmentService.releaseGradebookAssignment(associateGradebookAssignment, true); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId")); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // we are changing the view, so start with first page again. resetPaging(state); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE); } // doView_grade /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); String option = (String) params.getString("option"); if (option != null) { if (option.equals("post")) { // post assignment doPost_assignment(data); } else if (option.equals("save")) { // save assignment doSave_assignment(data); } else if (option.equals("preview")) { // preview assignment doPreview_assignment(data); } else if (option.equals("cancel")) { // cancel creating assignment doCancel_new_assignment(data); } else if (option.equals("canceledit")) { // cancel editing assignment doCancel_edit_assignment(data); } else if (option.equals("attach")) { // attachments doAttachments(data); } else if (option.equals("view")) { // view doView(data); } else if (option.equals("permissions")) { // permissions doPermissions(data); } else if (option.equals("returngrade")) { // return grading doReturn_grade_submission(data); } else if (option.equals("savegrade")) { // save grading doSave_grade_submission(data); } else if (option.equals("previewgrade")) { // preview grading doPreview_grade_submission(data); } else if (option.equals("cancelgrade")) { // cancel grading doCancel_grade_submission(data); } else if (option.equals("sortbygrouptitle")) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if (option.equals("sortbygroupdescription")) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if (option.equals("hide_instruction")) { // hide the assignment instruction doHide_submission_assignment_instruction(data); } else if (option.equals("show_instruction")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("sortbygroupdescription")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } } } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String mode = (String) state.getAttribute(STATE_MODE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); } } /** * readGradeForm */ public void readGradeForm(RunData data, SessionState state, String gradeOption) { ParameterParser params = data.getParameters(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = params.getCleanString(GRADE_SUBMISSION_GRADE); if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); Assignment a = AssignmentService.getSubmission(sId).getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // do grade validation only for Assignment with Grade tool if (typeOfGrade == 3) { if ((grade.length() == 0)) { if (gradeOption.equals("release")) { // in case of releasing grade, user must specify a grade addAlert(state, rb.getString("plespethe2")); } } else { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != 1) && gradeOption.equals("release")) { addAlert(state, rb.getString("plespethe2")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // allow resubmit number and due time if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM); state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); // validate date if (closeTime.before(TimeService.newTime())) { addAlert(state, rb.getString("assig4")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } } else { // reset the state attributes state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH); state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY); state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN); state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if /** The calendar service in the State. */ CalendarService cService = (CalendarService) state.getAttribute(STATE_CALENDAR_SERVICE); if (cService == null) { cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { Log.info("chef", "No calendar found for site " + siteId); state.removeAttribute(CALENDAR); } catch (PermissionException e) { Log.info("chef", "No permission to get the calender. "); state.removeAttribute(CALENDAR); } catch (Exception ex) { Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex); state.removeAttribute(CALENDAR); } } } // if /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { Log.warn("chef", "No announcement channel found. "); // the announcement channel is not created yet; go create try { aService.addAnnouncementChannel(channelId); } catch (PermissionException ee) { Log.warn("chef", "Can not create announcement channel. "); } catch (IdUsedException ee) { } catch (IdInvalidException ee) { Log.warn("chef", "The announcement channel could not be created because the Id is invalid. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : announcement exception : " + ex); } } catch (PermissionException e) { Log.warn("chef", "No permission to annoucement channel. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex); } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); } if (state.getAttribute(SORTED_ASC) == null) { state.setAttribute(SORTED_ASC, Boolean.FALSE.toString()); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null) { resetAssignment(state); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, new Boolean(withGrades)); } // whether the choice of emails instructor submission notification is available in the installation if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true))); } // whether or how the instructor receive submission notification emails, none(default)|each|digest if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } } // initState /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * reset the attributes for view submission */ private void resetAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); } // resetNewAssignment /** * construct a Hashtable using integer as the key and three character string of the month as the value */ private Hashtable monthTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("jan")); n.put(new Integer(2), rb.getString("feb")); n.put(new Integer(3), rb.getString("mar")); n.put(new Integer(4), rb.getString("apr")); n.put(new Integer(5), rb.getString("may")); n.put(new Integer(6), rb.getString("jun")); n.put(new Integer(7), rb.getString("jul")); n.put(new Integer(8), rb.getString("aug")); n.put(new Integer(9), rb.getString("sep")); n.put(new Integer(10), rb.getString("oct")); n.put(new Integer(11), rb.getString("nov")); n.put(new Integer(12), rb.getString("dec")); return n; } // monthTable /** * construct a Hashtable using the integer as the key and grade type String as the value */ private Hashtable gradeTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(2), rb.getString("letter")); n.put(new Integer(3), rb.getString("points")); n.put(new Integer(4), rb.getString("pass")); n.put(new Integer(5), rb.getString("check")); n.put(new Integer(1), rb.getString("ungra")); return n; } // gradeTypeTable /** * construct a Hashtable using the integer as the key and submission type String as the value */ private Hashtable submissionTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("inlin")); n.put(new Integer(2), rb.getString("attaonly")); n.put(new Integer(3), rb.getString("inlinatt")); n.put(new Integer(4), rb.getString("nonelec")); return n; } // submissionTypeTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the UserSubmission clas */ public class UserSubmission { /** * the User object */ User m_user = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; public UserSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { m_state = state; m_criteria = criteria; m_asc = asc; } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group rv = rv.concat(site.getGroup((String) k.next()).getTitle()); } } catch (Exception ignore) { } } return rv; } // getAssignmentRange /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; /** *********** fo sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { - String lName1 = u1.getUser().getLastName(); - String lName2 = u2.getUser().getLastName(); + String lName1 = u1.getUser().getSortName(); + String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare /** * get the submissin status */ private String getSubmissionStatus(SessionState state, AssignmentSubmission s) { String status = ""; if (s.getReturned()) { if (s.getTimeReturned() != null && s.getTimeSubmitted() != null && s.getTimeReturned().before(s.getTimeSubmitted())) { status = rb.getString("listsub.resubmi"); } else { status = rb.getString("gen.returned"); } } else if (s.getGraded()) { if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { status = rb.getString("grad3"); } else { status = rb.getString("gen.commented"); } } else { status = rb.getString("gen.ung1"); } return status; } // getSubmissionStatus /** * get the status string of assignment */ private String getAssignmentStatus(Assignment a) { String status = ""; Time currentTime = TimeService.newTime(); if (a.getDraft()) status = rb.getString("draft2"); else if (a.getOpenTime().after(currentTime)) status = rb.getString("notope"); else if (a.getDueTime().after(currentTime)) status = rb.getString("ope"); else if ((a.getCloseTime() != null) && (a.getCloseTime().before(currentTime))) status = rb.getString("clos"); else status = rb.getString("due2"); return status; } // getAssignmentStatus /** * get submission status */ private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment) { String status = ""; if (submission != null) if (submission.getSubmitted()) if (submission.getGraded() && submission.getGradeReleased()) status = rb.getString("grad3"); else if (submission.getReturned()) status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull(); else { status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull(); if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late"); } else status = rb.getString("inpro"); else status = rb.getString("notsta"); return status; } // getSubmissionStatus /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("nogra"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass2"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check2"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to Vector */ private Vector iterator_to_vector(Iterator l) { Vector v = new Vector(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_vector /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new Vector(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || !allowAddAssignment) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); try { String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted.equals("")) { // show not deleted assignments Time openTime = a.getOpenTime(); if (openTime != null && currentTime.after(openTime) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && AssignmentService.getSubmission(a.getReference(), (User) state .getAttribute(STATE_USER)) != null) { // and those deleted assignments but the user has made submissions to them returnResources.add(a); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } } } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { Vector submissions = new Vector(); Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING))); if (assignments.size() > 0) { // users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ()); } for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || deleted.equals("")) && (!a.getDraft())) { try { Vector assignmentSubmissions = iterator_to_vector(AssignmentService.getSubmissions(a)); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s .getTimeReturned()))))) { // has been subitted or has been returned and not work on it yet submissions.add(s); } // if-else } } catch (Exception e) { } } } returnResources = submissions; } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); Iterator submissionsIterator = AssignmentService.getSubmissions(a); List submissions = new Vector(); while (submissionsIterator.hasNext()) { submissions.add(submissionsIterator.next()); } // get all active site users String authzGroupId = SiteService.siteReference(contextString); // all users that can submit List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { boolean found = false; for (int i = 0; !found && i<submissions.size();i++) { AssignmentSubmission s = (AssignmentSubmission) submissions.get(i); if (s.getSubmitterIds().contains(userId)) { returnResources.add(new UserSubmission(u, s)); found = true; } } // add those users who haven't made any submissions if (!found) { // construct fake submissions for grading purpose AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId()); s.removeSubmitter(UserDirectoryService.getCurrentUser()); s.addSubmitter(u); s.setSubmitted(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); returnResources.add(new UserSubmission(u, sub)); } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } } } catch (Exception e) { Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && !sort.startsWith("sorted_grade_submission_by")) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && sort.startsWith("sorted_submission_by")) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending)); } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (viewMode.equals(MODE_LIST_ASSIGNMENTS)) { doList_assignments(data); } else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { doView_students_assignment(data); } else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { doReport_submissions(data); } else if (viewMode.equals(MODE_STUDENT_VIEW)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade? */ private void validPointGrade(SessionState state, String grade) { if (grade != null && !grade.equals("")) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { int index = grade.indexOf("."); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!grade.equals(".")) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } else { // grade is "." addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } } } // validPointGrade private void alertInvalidPoint(SessionState state, String grade) { String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, rb.getString("plesuse4") + maxInt + "." + maxDec + "."); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { if (grade.indexOf(".") != -1) { if (grade.startsWith(".")) { grade = "0".concat(grade); } else if (grade.endsWith(".")) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf("."); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if (point.equals("00")) { point = "0"; } } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuffer alertMsg = new StringBuffer(); try { boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } catch (Exception e) { Log.warn("chef", this + ": ", e); return strFromBrowser; } } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuffer buf = new StringBuffer(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors buf = new StringBuffer(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuffer buf = new StringBuffer(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuffer buf = new StringBuffer(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuffer buf = new StringBuffer(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION) || mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("cancel")) { // cancel doCancel_show_submission(data); } else if (option.equals("preview")) { // preview doPreview_submission(data); } else if (option.equals("save")) { // save draft doSave_submission(data); } else if (option.equals("post")) { // post doPost_submission(data); } else if (option.equals("revise")) { // done preview doDone_preview_submission(data); } else if (option.equals("attach")) { // attach doAttachments(data); } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = params.getString("defaultGrade"); String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List userSubmissions = new Vector(); if (state.getAttribute(USER_SUBMISSIONS) != null) { userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS); } // constructor a new UserSubmissions list List userSubmissionsNew = new Vector(); for (int i = 0; i<userSubmissions.size(); i++) { // get the UserSubmission object UserSubmission us = (UserSubmission) userSubmissions.get(i); User u = us.getUser(); AssignmentSubmission submission = us.getSubmission(); // check whether there is a submission associated if (submission == null) { AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId); s.removeSubmitter(UserDirectoryService.getCurrentUser()); s.addSubmitter(u); // submitted by without submit time s.setSubmitted(true); s.setGrade(grade); s.setGraded(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); userSubmissionsNew.add(new UserSubmission(u, sub)); } else if (submission.getTimeSubmitted() == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); sEdit.setAssignment(a); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else { // no change for this user userSubmissionsNew.add(us); } } state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew); } } catch (Exception e) { Log.warn("chef", e.toString()); } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } }
true
true
public int compare(Object o1, Object o2) { int result = -1; /** *********** fo sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getLastName(); String lName2 = u2.getUser().getLastName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare
public int compare(Object o1, Object o2) { int result = -1; /** *********** fo sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare
diff --git a/online-local/src/net/myrrix/online/generation/InputFilesReader.java b/online-local/src/net/myrrix/online/generation/InputFilesReader.java index 06479ce..836364f 100644 --- a/online-local/src/net/myrrix/online/generation/InputFilesReader.java +++ b/online-local/src/net/myrrix/online/generation/InputFilesReader.java @@ -1,165 +1,166 @@ /* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online.generation; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import com.google.common.base.Splitter; import com.google.common.io.PatternFilenameFilter; import org.apache.commons.math3.util.FastMath; import org.apache.mahout.common.iterator.FileLineIterable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.LangUtils; import net.myrrix.common.collection.FastByIDFloatMap; import net.myrrix.common.collection.FastByIDMap; import net.myrrix.common.collection.FastIDSet; import net.myrrix.common.io.InvertedFilenameFilter; import net.myrrix.common.math.MatrixUtils; /** * @author Sean Owen */ final class InputFilesReader { private static final Logger log = LoggerFactory.getLogger(InputFilesReader.class); private static final Splitter COMMA = Splitter.on(','); /** * Values with absolute value less than this in the input are considered 0. * Values are generally assumed to be > 1, actually, * and usually not negative, though they need not be. */ private static final float ZERO_THRESHOLD = Float.parseFloat(System.getProperty("model.decay.zeroThreshold", "0.0001")); private InputFilesReader() { } static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs, FastByIDMap<FastByIDFloatMap> rbyRow, FastByIDMap<FastByIDFloatMap> rbyColumn, File inputDir) throws IOException { FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"); File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter)); if (otherFiles != null) { for (File otherFile : otherFiles) { log.info("Skipping file {}", otherFile.getName()); } } File[] inputFiles = inputDir.listFiles(csvFilter); if (inputFiles == null) { log.info("No input files in {}", inputDir); return; } Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE); int lines = 0; int badLines = 0; for (File inputFile : inputFiles) { log.info("Reading {}", inputFile); for (CharSequence line : new FileLineIterable(inputFile)) { + lines++; Iterator<String> it = COMMA.split(line).iterator(); long userID; long itemID; float value; try { userID = Long.parseLong(it.next()); itemID = Long.parseLong(it.next()); if (it.hasNext()) { String valueToken = it.next().trim(); value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken); } else { value = 1.0f; } } catch (NoSuchElementException nsee) { log.warn("Ignoring line with too few columns: '{}'", line); if (++badLines > 100) { // Crude check throw new IOException("Too many bad lines; aborting"); } continue; } catch (IllegalArgumentException iae) { // includes NumberFormatException - if (lines == 0) { + if (lines == 1) { log.info("Ignoring header line"); } else { log.warn("Ignoring unparseable line: '{}'", line); if (++badLines > 100) { // Crude check throw new IOException("Too many bad lines; aborting"); } } continue; } if (Float.isNaN(value)) { // Remove, not set MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn); } else { MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn); } if (knownItemIDs != null) { FastIDSet itemIDs = knownItemIDs.get(userID); if (Float.isNaN(value)) { // Remove, not set if (itemIDs != null) { itemIDs.remove(itemID); if (itemIDs.isEmpty()) { knownItemIDs.remove(userID); } } } else { if (itemIDs == null) { itemIDs = new FastIDSet(); knownItemIDs.put(userID, itemIDs); } itemIDs.add(itemID); } } - if (++lines % 1000000 == 0) { + if (lines % 1000000 == 0) { log.info("Finished {} lines", lines); } } } removeSmall(rbyRow); removeSmall(rbyColumn); } private static void removeSmall(FastByIDMap<FastByIDFloatMap> matrix) { for (FastByIDMap.MapEntry<FastByIDFloatMap> entry : matrix.entrySet()) { for (Iterator<FastByIDFloatMap.MapEntry> it = entry.getValue().entrySet().iterator(); it.hasNext();) { FastByIDFloatMap.MapEntry entry2 = it.next(); if (FastMath.abs(entry2.getValue()) < ZERO_THRESHOLD) { it.remove(); } } } } }
false
true
static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs, FastByIDMap<FastByIDFloatMap> rbyRow, FastByIDMap<FastByIDFloatMap> rbyColumn, File inputDir) throws IOException { FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"); File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter)); if (otherFiles != null) { for (File otherFile : otherFiles) { log.info("Skipping file {}", otherFile.getName()); } } File[] inputFiles = inputDir.listFiles(csvFilter); if (inputFiles == null) { log.info("No input files in {}", inputDir); return; } Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE); int lines = 0; int badLines = 0; for (File inputFile : inputFiles) { log.info("Reading {}", inputFile); for (CharSequence line : new FileLineIterable(inputFile)) { Iterator<String> it = COMMA.split(line).iterator(); long userID; long itemID; float value; try { userID = Long.parseLong(it.next()); itemID = Long.parseLong(it.next()); if (it.hasNext()) { String valueToken = it.next().trim(); value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken); } else { value = 1.0f; } } catch (NoSuchElementException nsee) { log.warn("Ignoring line with too few columns: '{}'", line); if (++badLines > 100) { // Crude check throw new IOException("Too many bad lines; aborting"); } continue; } catch (IllegalArgumentException iae) { // includes NumberFormatException if (lines == 0) { log.info("Ignoring header line"); } else { log.warn("Ignoring unparseable line: '{}'", line); if (++badLines > 100) { // Crude check throw new IOException("Too many bad lines; aborting"); } } continue; } if (Float.isNaN(value)) { // Remove, not set MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn); } else { MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn); } if (knownItemIDs != null) { FastIDSet itemIDs = knownItemIDs.get(userID); if (Float.isNaN(value)) { // Remove, not set if (itemIDs != null) { itemIDs.remove(itemID); if (itemIDs.isEmpty()) { knownItemIDs.remove(userID); } } } else { if (itemIDs == null) { itemIDs = new FastIDSet(); knownItemIDs.put(userID, itemIDs); } itemIDs.add(itemID); } } if (++lines % 1000000 == 0) { log.info("Finished {} lines", lines); } } } removeSmall(rbyRow); removeSmall(rbyColumn); }
static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs, FastByIDMap<FastByIDFloatMap> rbyRow, FastByIDMap<FastByIDFloatMap> rbyColumn, File inputDir) throws IOException { FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"); File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter)); if (otherFiles != null) { for (File otherFile : otherFiles) { log.info("Skipping file {}", otherFile.getName()); } } File[] inputFiles = inputDir.listFiles(csvFilter); if (inputFiles == null) { log.info("No input files in {}", inputDir); return; } Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE); int lines = 0; int badLines = 0; for (File inputFile : inputFiles) { log.info("Reading {}", inputFile); for (CharSequence line : new FileLineIterable(inputFile)) { lines++; Iterator<String> it = COMMA.split(line).iterator(); long userID; long itemID; float value; try { userID = Long.parseLong(it.next()); itemID = Long.parseLong(it.next()); if (it.hasNext()) { String valueToken = it.next().trim(); value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken); } else { value = 1.0f; } } catch (NoSuchElementException nsee) { log.warn("Ignoring line with too few columns: '{}'", line); if (++badLines > 100) { // Crude check throw new IOException("Too many bad lines; aborting"); } continue; } catch (IllegalArgumentException iae) { // includes NumberFormatException if (lines == 1) { log.info("Ignoring header line"); } else { log.warn("Ignoring unparseable line: '{}'", line); if (++badLines > 100) { // Crude check throw new IOException("Too many bad lines; aborting"); } } continue; } if (Float.isNaN(value)) { // Remove, not set MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn); } else { MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn); } if (knownItemIDs != null) { FastIDSet itemIDs = knownItemIDs.get(userID); if (Float.isNaN(value)) { // Remove, not set if (itemIDs != null) { itemIDs.remove(itemID); if (itemIDs.isEmpty()) { knownItemIDs.remove(userID); } } } else { if (itemIDs == null) { itemIDs = new FastIDSet(); knownItemIDs.put(userID, itemIDs); } itemIDs.add(itemID); } } if (lines % 1000000 == 0) { log.info("Finished {} lines", lines); } } } removeSmall(rbyRow); removeSmall(rbyColumn); }
diff --git a/org.iucn.sis.server.api/src/org/iucn/sis/server/api/persistance/hibernate/AbstractORMCriteria.java b/org.iucn.sis.server.api/src/org/iucn/sis/server/api/persistance/hibernate/AbstractORMCriteria.java index 2b084ca3..fc138066 100644 --- a/org.iucn.sis.server.api/src/org/iucn/sis/server/api/persistance/hibernate/AbstractORMCriteria.java +++ b/org.iucn.sis.server.api/src/org/iucn/sis/server/api/persistance/hibernate/AbstractORMCriteria.java @@ -1,132 +1,133 @@ package org.iucn.sis.server.api.persistance.hibernate; import java.util.List; import org.hibernate.CacheMode; import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projection; import org.hibernate.transform.ResultTransformer; public abstract class AbstractORMCriteria implements Criteria { private final Criteria _criteria; public AbstractORMCriteria(Criteria criteria) { this._criteria = criteria; + setFlushMode(FlushMode.COMMIT); } public Criteria add(Criterion aCriterion) { return _criteria.add(aCriterion); } public Criteria addOrder(Order aOrder) { return _criteria.addOrder(aOrder); } public Criteria createAlias(String associationPath, String alias, int aJoinType) throws HibernateException { return _criteria.createAlias(associationPath, alias, aJoinType); } public Criteria createAlias(String associationPath, String alias) throws HibernateException { return _criteria.createAlias(associationPath, alias); } public Criteria createCriteria(String associationPath, int aJoinType) throws HibernateException { return _criteria.createCriteria(associationPath, aJoinType); } public Criteria createCriteria(String associationPath, String alias, int aJoinType) throws HibernateException { return _criteria.createCriteria(associationPath, alias, aJoinType); } public Criteria createCriteria(String associationPath, String alias) throws HibernateException { return _criteria.createCriteria(associationPath, alias); } public Criteria createCriteria(String associationPath) throws HibernateException { return _criteria.createCriteria(associationPath); } public String getAlias() { return _criteria.getAlias(); } public List list() throws HibernateException { return _criteria.list(); } public ScrollableResults scroll() throws HibernateException { return _criteria.scroll(); } public ScrollableResults scroll(ScrollMode aScrollMode) throws HibernateException { return _criteria.scroll(aScrollMode); } public Criteria setCacheable(boolean aCacheable) { return _criteria.setCacheable(aCacheable); } public Criteria setCacheMode(CacheMode aCacheMode) { return _criteria.setCacheMode(aCacheMode); } public Criteria setCacheRegion(String aCacheRegion) { return _criteria.setCacheRegion(aCacheRegion); } public Criteria setComment(String aComment) { return _criteria.setComment(aComment); } public Criteria setFetchMode(String associationPath, FetchMode aMode) throws HibernateException { return _criteria.setFetchMode(associationPath, aMode); } public Criteria setFetchSize(int aFetchSize) { return _criteria.setFetchSize(aFetchSize); } public Criteria setFirstResult(int aFirstResult) { return _criteria.setFirstResult(aFirstResult); } public Criteria setFlushMode(FlushMode aFlushMode) { return _criteria.setFlushMode(aFlushMode); } public Criteria setLockMode(LockMode aLockMode) { return _criteria.setLockMode(aLockMode); } public Criteria setLockMode(String alias, LockMode aLockMode) { return _criteria.setLockMode(alias, aLockMode); } public Criteria setMaxResults(int aMaxResults) { return _criteria.setMaxResults(aMaxResults); } public Criteria setProjection(Projection aProjection) { return _criteria.setProjection(aProjection); } public Criteria setResultTransformer(ResultTransformer aResultTransformer) { return _criteria.setResultTransformer(aResultTransformer); } public Criteria setTimeout(int aTimeout) { return _criteria.setTimeout(aTimeout); } public Object uniqueResult() throws HibernateException { return _criteria.uniqueResult(); } }
true
true
public AbstractORMCriteria(Criteria criteria) { this._criteria = criteria; }
public AbstractORMCriteria(Criteria criteria) { this._criteria = criteria; setFlushMode(FlushMode.COMMIT); }
diff --git a/src/impl/java/org/wyona/yanel/impl/resources/BasicXMLResource.java b/src/impl/java/org/wyona/yanel/impl/resources/BasicXMLResource.java index 5cef0617e..2bface2fa 100644 --- a/src/impl/java/org/wyona/yanel/impl/resources/BasicXMLResource.java +++ b/src/impl/java/org/wyona/yanel/impl/resources/BasicXMLResource.java @@ -1,522 +1,522 @@ /* * Copyright 2007-2009 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.wyona.org/licenses/APACHE-LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wyona.yanel.impl.resources; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationUtil; import org.apache.log4j.Logger; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.apache.xml.utils.ListingErrorHandler; import org.w3c.dom.Document; import org.wyona.commons.io.MimeTypeUtil; import org.wyona.security.core.api.Identity; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.SourceResolver; import org.wyona.yanel.core.transformation.I18nTransformer3; import org.wyona.yanel.core.transformation.XIncludeTransformer; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.impl.resources.xml.ConfigurableViewDescriptor; import org.wyona.yarep.core.Repository; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * It is a base class for resources that generate XML. Subclasses must override getContentXML * in order to pass XML for a view. * <p> * The class has its configuration for views ('default' and 'source' are built in). It resides in *.yanel-rc file, e.g. * <pre> * &lt;yanel:custom-config> * &lt;views> * &lt;!-- No parameter needed for getting this view --> * &lt;view id="default"> * &lt;mime-type>text/html&lt;/mime-type> * &lt;xslt>/xslt/global.xsl&lt;/xslt> * &lt;serializer key="HTML_TRANSITIONAL"> * &lt;/serializer> * &lt;/view> * * &lt;view id="beautiful"> * &lt;mime-type>application/xhtml+xml&lt;/mime-type> * &lt;xslt>/xslt/global.xsl&lt;/xslt> * &lt;serializer key="XHTML_STRICT"> * &lt;/serializer> * &lt;/view> * * &lt;view id="atom"> * &lt;mime-type>application/atom+xml&lt;/mime-type> * &lt;serializer key="XML"> * &lt;/serializer> * &lt;/view> * * &lt;view id="json"> * &lt;mime-type>application/json&lt;/mime-type> * &lt;serializer key="TEXT"> * &lt;/serializer> * &lt;/view> * * &lt;!-- Skips any provided XSLT--> * &lt;view id="source"> * &lt;mime-type>application/xhtml+xml&lt;/mime-type> * &lt;serializer key="XML"> * &lt;/serializer> * &lt;/view> *&lt;/views> *&lt;/yanel:custom-config> * </pre> * <p> * A view is accessed through a request parameter <b>yanel.resource.viewid</b> * <p> * If no serializer is specified for a view, the serializer will be chosen depending * on the mime-type, whereas the default serializer is XHTML_STRICT. * </p> */ public class BasicXMLResource extends Resource implements ViewableV2 { private static Logger log = Logger.getLogger(BasicXMLResource.class); protected static String DEFAULT_VIEW_ID = "default"; protected static String SOURCE_VIEW_ID = "source"; protected HashMap<String, ViewDescriptor> viewDescriptors; public ViewDescriptor getViewDescriptor(String viewId) { ViewDescriptor[] viewDescriptors = getViewDescriptors(); for (int i = 0; i < viewDescriptors.length; i++) { if (viewDescriptors[i].getId().equals(viewId)) { return viewDescriptors[i]; } } return null; } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getViewDescriptors() */ public ViewDescriptor[] getViewDescriptors() { if (this.viewDescriptors != null) { return this.viewDescriptors.values().toArray(new ViewDescriptor[this.viewDescriptors.size()]); } try { this.viewDescriptors = new HashMap<String, ViewDescriptor>(); // reads views from configuration: if (getConfiguration() != null && getConfiguration().getCustomConfiguration() != null) { Document customConfigDoc = getConfiguration().getCustomConfiguration(); Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement()); Configuration viewsConfig = config.getChild("views"); Configuration[] viewConfigs = viewsConfig.getChildren("view"); for (int i = 0; i < viewConfigs.length; i++) { String id = viewConfigs[i].getAttribute("id"); ConfigurableViewDescriptor viewDescriptor = new ConfigurableViewDescriptor(id); viewDescriptor.configure(viewConfigs[i]); this.viewDescriptors.put(id, viewDescriptor); } return this.viewDescriptors.values().toArray(new ViewDescriptor[this.viewDescriptors.size()]); } // no custom config ConfigurableViewDescriptor[] vd = new ConfigurableViewDescriptor[2]; vd[0] = new ConfigurableViewDescriptor(DEFAULT_VIEW_ID); String mimeType = getResourceConfigProperty("mime-type"); vd[0].setMimeType(mimeType); this.viewDescriptors.put(DEFAULT_VIEW_ID, vd[0]); vd[1] = new ConfigurableViewDescriptor(SOURCE_VIEW_ID); mimeType = getResourceConfigProperty("source-view-mime-type"); vd[1].setMimeType(mimeType); this.viewDescriptors.put(SOURCE_VIEW_ID, vd[1]); return vd; } catch (Exception e) { String errorMsg = "Error configuring resource: " + getPath() + ": " + e.toString(); log.error(errorMsg, e); // TODO: throw exception return null; } } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getView(java.lang.String) */ public View getView(String viewId) throws Exception { return getXMLView(viewId, getContentXML(viewId)); } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getMimeType(java.lang.String) */ public String getMimeType(String viewId) throws Exception { String mimeType = null; ViewDescriptor viewDescriptor = getViewDescriptor(viewId); if (viewDescriptor != null) { mimeType = viewDescriptor.getMimeType(); } if (mimeType == null) { mimeType = this.getResourceConfigProperty("mime-type"); } if (mimeType == null) { mimeType = "application/xhtml+xml"; log.warn("No mime type configured, hence will return '" + mimeType + "' as mime type!"); } //log.debug("Mime type: " + mimeType + ", " + viewId); return mimeType; } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#exists() */ public boolean exists() throws Exception { return getRealm().getRepository().existsNode(getPath()); } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getSize() */ public long getSize() throws Exception { return -1; } public View getXMLView(String viewId, InputStream xmlInputStream) throws Exception { View view = new View(); if (viewId == null) { viewId = DEFAULT_VIEW_ID; } ConfigurableViewDescriptor viewDescriptor = (ConfigurableViewDescriptor)getViewDescriptor(viewId); String mimeType = getMimeType(viewId); view.setMimeType(mimeType); StringWriter errorWriter = new StringWriter(); try { if (viewId != null && viewId.equals(SOURCE_VIEW_ID)) { view.setInputStream(xmlInputStream); return view; } // write result into view: view.setInputStream(getTransformedInputStream(xmlInputStream, viewDescriptor, errorWriter)); return view; } catch(Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")", e); String errorMsg; String transformationError = errorWriter.toString(); if (transformationError != null) { errorMsg = "Transformation error:\n" + transformationError; log.error(errorMsg); } else { errorMsg = e.getMessage(); } throw new Exception(errorMsg); } } private InputStream getTransformedInputStream(InputStream xmlInputStream, ConfigurableViewDescriptor viewDescriptor, StringWriter errorWriter) throws Exception { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SourceResolver uriResolver = new SourceResolver(this); ListingErrorHandler errorListener = new ListingErrorHandler(new PrintWriter(errorWriter)); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory)TransformerFactory.newInstance(); tf.setURIResolver(uriResolver); tf.setErrorListener(errorListener); String[] xsltPaths = viewDescriptor.getXSLTPaths(); if (xsltPaths == null || xsltPaths.length == 0) { xsltPaths = getXSLTPath(getPath()); } Repository repo = getRealm().getRepository(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPaths.length]; for (int i = 0; i < xsltPaths.length; i++) { String xsltPath = xsltPaths[i]; int schemeEndIndex = xsltPath.indexOf(':'); if (xsltPaths[i].startsWith("file:")) { // TODO: Handle "file:" in SourceResolver log.info("Scheme: file (" + xsltPaths[i] + ")"); - xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(new java.io.FileInputStream(xsltPaths[i].substring(5)))); + xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(new java.io.FileInputStream(xsltPaths[i].substring(5)), xsltPaths[i])); } else if (schemeEndIndex >= 0) { String scheme = xsltPath.substring(0, schemeEndIndex); log.info("Scheme: " + scheme + " (" + xsltPath + ")"); - xsltHandlers[i] = tf.newTransformerHandler(uriResolver.resolve(xsltPath, null)); + xsltHandlers[i] = tf.newTransformerHandler(uriResolver.resolve(xsltPath, xsltPath)); /*XXX BACKWARD-COMPATIBILITY from now on we throw new SourceException("No resolver could be loaded for scheme: " + scheme); instead of simply only doing log.error("No such protocol implemented: " + xsltPaths[i].substring(0, xsltPaths[i].indexOf(":/"))); and then probably also throwing some other exception anyway... */ } else { if (log.isDebugEnabled()) { log.debug("Default Content repository will be used!"); } xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPaths[i]).getInputStream(), "yanelrepo:" + xsltPaths[i])); } xsltHandlers[i].getTransformer().setURIResolver(uriResolver); xsltHandlers[i].getTransformer().setErrorListener(errorListener); passTransformerParameters(xsltHandlers[i].getTransformer()); } // create i18n transformer: I18nTransformer3 i18nTransformer = new I18nTransformer3(getI18NCatalogueNames(), getRequestedLanguage(), getRealm().getDefaultLanguage(), uriResolver); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); xIncludeTransformer.setResolver(uriResolver); // create serializer: Serializer serializer = createSerializer(viewDescriptor); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): if (xsltHandlers.length > 0) { xmlReader.setContentHandler(xsltHandlers[0]); for (int i=0; i<xsltHandlers.length-1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i+1])); } xsltHandlers[xsltHandlers.length-1].setResult(new SAXResult(xIncludeTransformer)); } else { xmlReader.setContentHandler(new SAXResult(xIncludeTransformer).getHandler()); } xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(xmlInputStream)); return new ByteArrayInputStream(baos.toByteArray()); } /** * Creates an html or xml serializer for the given view id. * @param viewId * @return serializer * @throws Exception */ protected Serializer createSerializer(ConfigurableViewDescriptor viewDescriptor) throws Exception { Serializer serializer = null; String serializerKey = viewDescriptor.getSerializerKey(); if (serializerKey != null) { serializer = SerializerFactory.getSerializer(serializerKey); if (serializer == null) { throw new Exception("could not create serializer for key: " + serializerKey); } } else { String mimeType = getMimeType(viewDescriptor.getId()); if (MimeTypeUtil.isHTML(mimeType) && !MimeTypeUtil.isXML(mimeType)) { serializer = SerializerFactory.getSerializer(SerializerFactory.HTML_TRANSITIONAL); } else if (MimeTypeUtil.isHTML(mimeType) && MimeTypeUtil.isXML(mimeType)){ serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); } else if (MimeTypeUtil.isXML(mimeType)) { serializer = SerializerFactory.getSerializer(SerializerFactory.XML); } else if (MimeTypeUtil.isTextual(mimeType)) { serializer = SerializerFactory.getSerializer(SerializerFactory.TEXT); } else{ // For backwards compatibility leave XHTML as default serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); } } // allow to override xml declaration and doctype: Properties properties = viewDescriptor.getSerializerProperties(); if (properties != null) { Enumeration<?> propNames = properties.propertyNames(); while (propNames.hasMoreElements()) { String name = (String)propNames.nextElement(); String value = properties.getProperty(name); serializer.getOutputFormat().setProperty(name, value); } } return serializer; } /** * Gets the names of the i18n message catalogues used for the i18n transformation. * Uses the following priorization: * 1. rc config properties named 'i18n-catalogue'. * 2. realm i18n-catalogue * 3. 'global' * @return i18n catalogue name */ protected String[] getI18NCatalogueNames() throws Exception { ArrayList<String> catalogues = new ArrayList<String>(); String[] rcCatalogues = getResourceConfigProperties("i18n-catalogue"); if (rcCatalogues != null) { for (int i = 0; i < rcCatalogues.length; i++) { catalogues.add(rcCatalogues[i]); } } String realmCatalogue = getRealm().getI18nCatalogue(); if (realmCatalogue != null) { catalogues.add(realmCatalogue); } catalogues.add("global"); return catalogues.toArray(new String[catalogues.size()]); } /** * Pass parameters to xslt transformer. * @param transformer * @throws Exception */ protected void passTransformerParameters(Transformer transformer) throws Exception { // Set general parameters transformer.setParameter("yanel.path.name", org.wyona.commons.io.PathUtil.getName(getPath())); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); transformer.setParameter("yanel.globalHtdocsPath", PathUtil.getGlobalHtdocsPath(this)); transformer.setParameter("yanel.resourcesHtdocsPath", PathUtil.getResourcesHtdocsPathURLencoded(this)); String backToRealm = PathUtil.backToRealm(getPath()); transformer.setParameter("yanel.back2realm", backToRealm); transformer.setParameter("yarep.back2realm", backToRealm); // for backwards compatibility // Set OS and client javax.servlet.http.HttpServletRequest request = getEnvironment().getRequest(); String userAgent = request.getHeader("User-Agent"); if (userAgent == null) { log.warn("Header contains no User-Agent!"); userAgent = "null"; } transformer.setParameter("language", getRequestedLanguage()); String os = getOS(userAgent); if (os != null) transformer.setParameter("os", os); String client = getClient(userAgent); if (client != null) transformer.setParameter("client", client); // Set query string String queryString = request.getQueryString(); if (queryString != null) { transformer.setParameter("yanel.request.query-string", queryString); } // localization transformer.setParameter("language", getRequestedLanguage()); // language of this translation transformer.setParameter("content-language", getContentLanguage()); // username String username = getUsername(); if (username != null) transformer.setParameter("username", username); transformer.setParameter("yanel.reservedPrefix", this.getYanel().getReservedPrefix()); // Add toolbar status String toolbarStatus = getToolbarStatus(); if (toolbarStatus != null) transformer.setParameter("yanel.toolbar-status", toolbarStatus); } /** * Gets the XML content which will be fed into the processing pipeline. * @return xml stream * @throws Exception */ protected InputStream getContentXML(String viewId) throws Exception { return getRealm().getRepository().getNode(getPath()).getInputStream(); } /** * Get operating system */ protected String getOS(String userAgent) { if (userAgent.indexOf("Linux") > 0) { return "unix"; } else if (userAgent.indexOf("Mac OS X") > 0) { return "unix"; } else if (userAgent.indexOf("Windows") > 0) { return "windows"; } else { log.warn("Operating System could not be recognized: " + userAgent); return null; } } /** * Get client */ protected String getClient(String userAgent) { if (userAgent.indexOf("Firefox") > 0) { return "firefox"; } else if (userAgent.indexOf("MSIE") > 0) { return "msie"; } else { if (log.isDebugEnabled()) log.debug("Client could not be recognized: " + userAgent); return null; } } /** * Get username from session */ protected String getUsername() { Identity identity = getEnvironment().getIdentity(); if (identity != null) return identity.getUsername(); return null; } /** * Get toolbar status from session */ protected String getToolbarStatus() { // TODO: Use YanelServlet.TOOLBAR_KEY instead "toolbar"! javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true); if (session != null) { return (String) session.getAttribute("toolbar"); } log.warn("No session exists or could be created!"); return null; } /** * Get XSLT path */ protected String[] getXSLTPath(String path) throws Exception { String[] xsltPath = getResourceConfigProperties("xslt"); if (xsltPath != null) return xsltPath; log.info("No XSLT Path within: " + path); return new String[0]; } }
false
true
private InputStream getTransformedInputStream(InputStream xmlInputStream, ConfigurableViewDescriptor viewDescriptor, StringWriter errorWriter) throws Exception { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SourceResolver uriResolver = new SourceResolver(this); ListingErrorHandler errorListener = new ListingErrorHandler(new PrintWriter(errorWriter)); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory)TransformerFactory.newInstance(); tf.setURIResolver(uriResolver); tf.setErrorListener(errorListener); String[] xsltPaths = viewDescriptor.getXSLTPaths(); if (xsltPaths == null || xsltPaths.length == 0) { xsltPaths = getXSLTPath(getPath()); } Repository repo = getRealm().getRepository(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPaths.length]; for (int i = 0; i < xsltPaths.length; i++) { String xsltPath = xsltPaths[i]; int schemeEndIndex = xsltPath.indexOf(':'); if (xsltPaths[i].startsWith("file:")) { // TODO: Handle "file:" in SourceResolver log.info("Scheme: file (" + xsltPaths[i] + ")"); xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(new java.io.FileInputStream(xsltPaths[i].substring(5)))); } else if (schemeEndIndex >= 0) { String scheme = xsltPath.substring(0, schemeEndIndex); log.info("Scheme: " + scheme + " (" + xsltPath + ")"); xsltHandlers[i] = tf.newTransformerHandler(uriResolver.resolve(xsltPath, null)); /*XXX BACKWARD-COMPATIBILITY from now on we throw new SourceException("No resolver could be loaded for scheme: " + scheme); instead of simply only doing log.error("No such protocol implemented: " + xsltPaths[i].substring(0, xsltPaths[i].indexOf(":/"))); and then probably also throwing some other exception anyway... */ } else { if (log.isDebugEnabled()) { log.debug("Default Content repository will be used!"); } xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPaths[i]).getInputStream(), "yanelrepo:" + xsltPaths[i])); } xsltHandlers[i].getTransformer().setURIResolver(uriResolver); xsltHandlers[i].getTransformer().setErrorListener(errorListener); passTransformerParameters(xsltHandlers[i].getTransformer()); } // create i18n transformer: I18nTransformer3 i18nTransformer = new I18nTransformer3(getI18NCatalogueNames(), getRequestedLanguage(), getRealm().getDefaultLanguage(), uriResolver); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); xIncludeTransformer.setResolver(uriResolver); // create serializer: Serializer serializer = createSerializer(viewDescriptor); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): if (xsltHandlers.length > 0) { xmlReader.setContentHandler(xsltHandlers[0]); for (int i=0; i<xsltHandlers.length-1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i+1])); } xsltHandlers[xsltHandlers.length-1].setResult(new SAXResult(xIncludeTransformer)); } else { xmlReader.setContentHandler(new SAXResult(xIncludeTransformer).getHandler()); } xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(xmlInputStream)); return new ByteArrayInputStream(baos.toByteArray()); }
private InputStream getTransformedInputStream(InputStream xmlInputStream, ConfigurableViewDescriptor viewDescriptor, StringWriter errorWriter) throws Exception { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SourceResolver uriResolver = new SourceResolver(this); ListingErrorHandler errorListener = new ListingErrorHandler(new PrintWriter(errorWriter)); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory)TransformerFactory.newInstance(); tf.setURIResolver(uriResolver); tf.setErrorListener(errorListener); String[] xsltPaths = viewDescriptor.getXSLTPaths(); if (xsltPaths == null || xsltPaths.length == 0) { xsltPaths = getXSLTPath(getPath()); } Repository repo = getRealm().getRepository(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPaths.length]; for (int i = 0; i < xsltPaths.length; i++) { String xsltPath = xsltPaths[i]; int schemeEndIndex = xsltPath.indexOf(':'); if (xsltPaths[i].startsWith("file:")) { // TODO: Handle "file:" in SourceResolver log.info("Scheme: file (" + xsltPaths[i] + ")"); xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(new java.io.FileInputStream(xsltPaths[i].substring(5)), xsltPaths[i])); } else if (schemeEndIndex >= 0) { String scheme = xsltPath.substring(0, schemeEndIndex); log.info("Scheme: " + scheme + " (" + xsltPath + ")"); xsltHandlers[i] = tf.newTransformerHandler(uriResolver.resolve(xsltPath, xsltPath)); /*XXX BACKWARD-COMPATIBILITY from now on we throw new SourceException("No resolver could be loaded for scheme: " + scheme); instead of simply only doing log.error("No such protocol implemented: " + xsltPaths[i].substring(0, xsltPaths[i].indexOf(":/"))); and then probably also throwing some other exception anyway... */ } else { if (log.isDebugEnabled()) { log.debug("Default Content repository will be used!"); } xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPaths[i]).getInputStream(), "yanelrepo:" + xsltPaths[i])); } xsltHandlers[i].getTransformer().setURIResolver(uriResolver); xsltHandlers[i].getTransformer().setErrorListener(errorListener); passTransformerParameters(xsltHandlers[i].getTransformer()); } // create i18n transformer: I18nTransformer3 i18nTransformer = new I18nTransformer3(getI18NCatalogueNames(), getRequestedLanguage(), getRealm().getDefaultLanguage(), uriResolver); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); xIncludeTransformer.setResolver(uriResolver); // create serializer: Serializer serializer = createSerializer(viewDescriptor); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): if (xsltHandlers.length > 0) { xmlReader.setContentHandler(xsltHandlers[0]); for (int i=0; i<xsltHandlers.length-1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i+1])); } xsltHandlers[xsltHandlers.length-1].setResult(new SAXResult(xIncludeTransformer)); } else { xmlReader.setContentHandler(new SAXResult(xIncludeTransformer).getHandler()); } xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(xmlInputStream)); return new ByteArrayInputStream(baos.toByteArray()); }
diff --git a/DataDemo/src/main/java/edu/unca/rbruce/DataDemo/DataDemoCommandExecutor.java b/DataDemo/src/main/java/edu/unca/rbruce/DataDemo/DataDemoCommandExecutor.java index 03e08ad..34aaa87 100644 --- a/DataDemo/src/main/java/edu/unca/rbruce/DataDemo/DataDemoCommandExecutor.java +++ b/DataDemo/src/main/java/edu/unca/rbruce/DataDemo/DataDemoCommandExecutor.java @@ -1,61 +1,61 @@ package edu.unca.rbruce.DataDemo; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.google.common.base.Joiner; /* * This is a sample CommandExectuor */ public class DataDemoCommandExecutor implements CommandExecutor { private final DataDemo plugin; /* * This command executor needs to know about its plugin from which it came * from */ public DataDemoCommandExecutor(DataDemo plugin) { this.plugin = plugin; } /* * On command set the sample message */ public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "you must be logged on to use these commands"); return false; } else if (command.getName().equalsIgnoreCase("god") && sender.hasPermission("DataDemo.god")) { Player fred = (Player) sender; plugin.setMetadata(fred, "god", true, plugin); sender.sendMessage(ChatColor.RED + fred.getName() + " you are a god now"); plugin.logger.info(fred.getName() + " has been made a god"); return true; } else if (command.getName().equalsIgnoreCase("human") && sender.hasPermission("DataDemo.god")) { Player fred = (Player) sender; plugin.setMetadata(fred, "god", false, plugin); sender.sendMessage(ChatColor.RED + fred.getName() + " you are human now"); plugin.logger.info(fred.getName() + " is no longer a god"); return true; } else if (command.getName().equalsIgnoreCase("message") - && sender.hasPermission("DataDemo.message") && args.length == 0) { + && sender.hasPermission("DataDemo.message") && args.length > 0) { this.plugin.getConfig().set("sample.message", Joiner.on(' ').join(args)); return true; } else { return false; } } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "you must be logged on to use these commands"); return false; } else if (command.getName().equalsIgnoreCase("god") && sender.hasPermission("DataDemo.god")) { Player fred = (Player) sender; plugin.setMetadata(fred, "god", true, plugin); sender.sendMessage(ChatColor.RED + fred.getName() + " you are a god now"); plugin.logger.info(fred.getName() + " has been made a god"); return true; } else if (command.getName().equalsIgnoreCase("human") && sender.hasPermission("DataDemo.god")) { Player fred = (Player) sender; plugin.setMetadata(fred, "god", false, plugin); sender.sendMessage(ChatColor.RED + fred.getName() + " you are human now"); plugin.logger.info(fred.getName() + " is no longer a god"); return true; } else if (command.getName().equalsIgnoreCase("message") && sender.hasPermission("DataDemo.message") && args.length == 0) { this.plugin.getConfig().set("sample.message", Joiner.on(' ').join(args)); return true; } else { return false; } }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "you must be logged on to use these commands"); return false; } else if (command.getName().equalsIgnoreCase("god") && sender.hasPermission("DataDemo.god")) { Player fred = (Player) sender; plugin.setMetadata(fred, "god", true, plugin); sender.sendMessage(ChatColor.RED + fred.getName() + " you are a god now"); plugin.logger.info(fred.getName() + " has been made a god"); return true; } else if (command.getName().equalsIgnoreCase("human") && sender.hasPermission("DataDemo.god")) { Player fred = (Player) sender; plugin.setMetadata(fred, "god", false, plugin); sender.sendMessage(ChatColor.RED + fred.getName() + " you are human now"); plugin.logger.info(fred.getName() + " is no longer a god"); return true; } else if (command.getName().equalsIgnoreCase("message") && sender.hasPermission("DataDemo.message") && args.length > 0) { this.plugin.getConfig().set("sample.message", Joiner.on(' ').join(args)); return true; } else { return false; } }
diff --git a/src/test/java/org/suite/RbTreeTest.java b/src/test/java/org/suite/RbTreeTest.java index 919cf4cd2..fbfefa017 100644 --- a/src/test/java/org/suite/RbTreeTest.java +++ b/src/test/java/org/suite/RbTreeTest.java @@ -1,25 +1,25 @@ package org.suite; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.Test; import org.suite.kb.RuleSet; import org.suite.kb.RuleSet.RuleSetUtil; public class RbTreeTest { @Test public void test() throws IOException { RuleSet rs = RuleSetUtil.create(); SuiteUtil.importResource(rs, "auto.sl"); - SuiteUtil.importResource(rs, "rb-tree.sl"); + SuiteUtil.importResource(rs, "rbt.sl"); assertTrue(SuiteUtil.proveThis(rs, "" // - + "rb-add-list (6, 7, 8, 9, 10, 1, 2, 3, 4, 5,) ()/.t \n" // - + ", rb-get .t 8" // - + ", rb-member .t 4")); + + "rbt-add-list (6, 7, 8, 9, 10, 1, 2, 3, 4, 5,) ()/.t \n" // + + ", rbt-get .t 8" // + + ", rbt-member .t 4")); } }
false
true
public void test() throws IOException { RuleSet rs = RuleSetUtil.create(); SuiteUtil.importResource(rs, "auto.sl"); SuiteUtil.importResource(rs, "rb-tree.sl"); assertTrue(SuiteUtil.proveThis(rs, "" // + "rb-add-list (6, 7, 8, 9, 10, 1, 2, 3, 4, 5,) ()/.t \n" // + ", rb-get .t 8" // + ", rb-member .t 4")); }
public void test() throws IOException { RuleSet rs = RuleSetUtil.create(); SuiteUtil.importResource(rs, "auto.sl"); SuiteUtil.importResource(rs, "rbt.sl"); assertTrue(SuiteUtil.proveThis(rs, "" // + "rbt-add-list (6, 7, 8, 9, 10, 1, 2, 3, 4, 5,) ()/.t \n" // + ", rbt-get .t 8" // + ", rbt-member .t 4")); }
diff --git a/bndtools.diff/src/bndtools/diff/JarDiff.java b/bndtools.diff/src/bndtools/diff/JarDiff.java index edf7b5f4..e9d8b5f8 100644 --- a/bndtools.diff/src/bndtools/diff/JarDiff.java +++ b/bndtools.diff/src/bndtools/diff/JarDiff.java @@ -1,1039 +1,1041 @@ /******************************************************************************* * Copyright (c) 2010 Per Kr. Soreide. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Per Kr. Soreide - initial API and implementation *******************************************************************************/ package bndtools.diff; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.security.MessageDigest; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import org.osgi.framework.Constants; import org.osgi.framework.Version; import aQute.bnd.build.Project; import aQute.bnd.service.RepositoryPlugin; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Jar; import aQute.lib.osgi.Resource; import aQute.libg.header.Attrs; import aQute.libg.header.Parameters; import aQute.libg.version.VersionRange; public class JarDiff { public static final int PKG_SEVERITY_NONE = 0; public static final int PKG_SEVERITY_MICRO = 10; // Version missing on exported package, or bytecode modification public static final int PKG_SEVERITY_MINOR = 20; // Method or class added public static final int PKG_SEVERITY_MAJOR = 30; // Class deleted, method changed or deleted private static final String VERSION = "version"; protected Map<String, PackageInfo> packages = new TreeMap<String, PackageInfo>(); protected String bundleSymbolicName; private TreeSet<String> suggestedVersions; private String selectedVersion; private String currentVersion; private final Jar projectJar; private final Jar previousJar; private RepositoryPlugin baselineRepository; private RepositoryPlugin releaseRepository; public JarDiff(Jar projectJar, Jar previousJar) { suggestedVersions = new TreeSet<String>(); this.projectJar = projectJar; this.previousJar = previousJar; } public void compare() throws Exception { Manifest projectManifest = projectJar.getManifest(); Parameters projectExportedPackages = new Parameters(getAttribute(projectManifest, Constants.EXPORT_PACKAGE)); Parameters projectImportedPackages = new Parameters(getAttribute(projectManifest, Constants.IMPORT_PACKAGE)); bundleSymbolicName = stripInstructions(getAttribute(projectManifest, Constants.BUNDLE_SYMBOLICNAME)); currentVersion = removeVersionQualifier(getAttribute(projectManifest, Constants.BUNDLE_VERSION)); // This is the version from the .bnd file Parameters previousExportedPackages; Parameters previousImportedPackages; Manifest previousManifest = null; if (previousJar != null) { previousManifest = previousJar.getManifest(); previousExportedPackages = new Parameters(getAttribute(previousManifest, Constants.EXPORT_PACKAGE)); previousImportedPackages = new Parameters(getAttribute(previousManifest, Constants.IMPORT_PACKAGE)); // If no version in projectJar use previous version if (currentVersion == null) { currentVersion = removeVersionQualifier(getAttribute(previousManifest, Constants.BUNDLE_VERSION)); } } else { previousExportedPackages = new Parameters(); // empty previousImportedPackages = new Parameters(); // empty } String prevName = stripInstructions(getAttribute(previousManifest, Constants.BUNDLE_SYMBOLICNAME)); if (bundleSymbolicName != null && prevName != null && !bundleSymbolicName.equals(prevName)) { throw new IllegalArgumentException(Constants.BUNDLE_SYMBOLICNAME + " must be equal"); } // Private packages if (previousJar != null) { for (String packageName : projectJar.getPackages()) { if (!projectExportedPackages.containsKey(packageName)) { PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); } Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, null); if (projectClasses.size() == 0) { continue; } if (!packages.containsKey(packageName)) { packages.put(packageName, pi); } Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, null); Set<ClassInfo> cis = pi.getClasses(); for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } cis.add(ci); if (prevCi != null && !Arrays.equals(ci.getSHA1(), prevCi.getSHA1())) { ci.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } if (prevCi == null) { ci.setChangeCode(ClassInfo.CHANGE_CODE_NEW); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } } if (previousClasses != null) { for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { cis.add(prevCi); prevCi.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); } } } } } } for (Entry<String, Attrs> entry : projectImportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); Map<String, String> packageMap = entry.getValue(); String version = packageMap.get(VERSION); VersionRange projectVersion = null; if (version != null) { projectVersion = new VersionRange(version); pi.setSuggestedVersionRange(projectVersion.toString()); } if (previousImportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); version = prevPackageMap.get(VERSION); VersionRange previousVersion = null; if (version != null) { previousVersion = new VersionRange(version); } // No change, no versions if (projectVersion == null && previousVersion == null) { continue; } // No change if (projectVersion != null && previousVersion != null) { if (projectVersion.getHigh().equals(previousVersion.getHigh()) && projectVersion.getLow().equals(previousVersion.getLow())) { pi.setVersionRange(previousVersion.toString()); continue; } pi.setSeverity(PKG_SEVERITY_MINOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (projectVersion != null) { pi.setSeverity(PKG_SEVERITY_MAJOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (previousVersion != null) { pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); } } } - for (String packageName : previousImportedPackages.keySet()) { + for (Entry<String, Attrs> entry : previousImportedPackages.entrySet()) { + String packageName = entry.getKey(); if (!projectImportedPackages.containsKey(packageName)) { // Removed Packages - Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); + Map<String, String> prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); pi.setVersionRange(previousVersion); } } - for (String packageName : projectExportedPackages.keySet()) { + for (Entry<String, Attrs> entry : projectExportedPackages.entrySet()) { + String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); - Map<String, String> packageMap = projectExportedPackages.get(packageName); + Map<String, String> packageMap = entry.getValue(); String packageVersion = removeVersionQualifier(packageMap.get(VERSION)); Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, packageVersion); Set<ClassInfo> cis = pi.getClasses(); String previousVersion = null; Set<ClassInfo> previousClasses = null; if (previousExportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); previousVersion = prevPackageMap.get(VERSION); previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); } for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } int severity = getModificationSeverity(ci, prevCi); cis.add(ci); if (severity > PKG_SEVERITY_NONE) { // New or modified class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } } } if (pi.getSeverity() > PKG_SEVERITY_NONE) { if (previousClasses == null) { // New package pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.addSuggestedVersion(packageVersion); } else { // Modified package pi.setCurrentVersion(previousVersion); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } if (pi.getSeverity() == PKG_SEVERITY_NONE) { if (previousClasses != null && previousVersion == null) { // No change, but version missing on package pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_VERSION_MISSING); pi.addSuggestedVersion(getCurrentVersion()); } } if (previousClasses != null) { pi.setCurrentVersion(previousVersion); for (ClassInfo prevCi : previousClasses) { if (projectClasses != null && !projectClasses.contains(prevCi)) { int severity = getModificationSeverity(null, prevCi); cis.add(prevCi); if (severity > PKG_SEVERITY_NONE) { // Removed class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } } } } for (String packageName : previousExportedPackages.keySet()) { if (!projectExportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); pi.setClasses(previousClasses); pi.setSeverity(PKG_SEVERITY_MAJOR); for (ClassInfo prevCi : previousClasses) { // Removed class getModificationSeverity(null, prevCi); } pi.setCurrentVersion(previousVersion); } } } private int getModificationSeverity(ClassInfo clazz, ClassInfo previousClass) { int severity = PKG_SEVERITY_NONE; if (clazz != null) { for (MethodInfo method : clazz.getMethods()) { MethodInfo prevMethod = findMethod(previousClass, method); if (prevMethod == null) { severity = PKG_SEVERITY_MINOR; method.setChangeCode(MethodInfo.CHANGE_NEW); } } for (FieldInfo field : clazz.getFields()) { FieldInfo prevField = findField(previousClass, field); if (prevField == null) { severity = PKG_SEVERITY_MINOR; field.setChangeCode(FieldInfo.CHANGE_NEW); } } } if (previousClass != null) { for (MethodInfo prevMethod : previousClass.getMethods()) { MethodInfo method = findMethod(clazz, prevMethod); if (method == null) { severity = PKG_SEVERITY_MAJOR; prevMethod.setChangeCode(MethodInfo.CHANGE_REMOVED); if (clazz != null) { clazz.addPublicMethod(prevMethod); } } } for (FieldInfo prevField : previousClass.getFields()) { FieldInfo method = findField(clazz, prevField); if (method == null) { severity = PKG_SEVERITY_MAJOR; prevField.setChangeCode(FieldInfo.CHANGE_REMOVED); if (clazz != null) { clazz.addPublicField(prevField); } } } } if (clazz != null && previousClass != null) { if (severity > PKG_SEVERITY_NONE) { clazz.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); } else { if (!Arrays.equals(clazz.getSHA1(), previousClass.getSHA1())) { clazz.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); severity = PKG_SEVERITY_MICRO; } else { clazz.setChangeCode(ClassInfo.CHANGE_CODE_NONE); } } } else if (previousClass == null) { clazz.setChangeCode(ClassInfo.CHANGE_CODE_NEW); if (severity == PKG_SEVERITY_NONE) { severity = PKG_SEVERITY_MINOR; } } else if (clazz == null) { previousClass.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); if (severity == PKG_SEVERITY_NONE) { severity = PKG_SEVERITY_MAJOR; } } return severity; } private MethodInfo findMethod(ClassInfo info, MethodInfo methodToFind) { if (info == null) { return null; } for (MethodInfo method : info.getMethods()) { if (!method.getName().equals(methodToFind.getName())) { continue; } if (method.getDesc() != null && !method.getDesc().equals(methodToFind.getDesc())) { continue; } return method; } return null; } private FieldInfo findField(ClassInfo info, FieldInfo fieldToFind) { if (info == null) { return null; } for (FieldInfo field : info.getFields()) { if (!field.getName().equals(fieldToFind.getName())) { continue; } if (field.getDesc() != null && !field.getDesc().equals(fieldToFind.getDesc())) { continue; } return field; } return null; } private static Set<ClassInfo> getClassesFromPackage(PackageInfo pi, Jar jar, String packageName, String version) { packageName = packageName.replace('.', '/'); Map<String, Map<String, Resource>> dirs = jar.getDirectories(); if (dirs == null) { return Collections.emptySet(); } Map<String, Resource> res = dirs.get(packageName); if (res == null) { return Collections.emptySet(); } Set<ClassInfo> ret = new TreeSet<ClassInfo>(); for (Map.Entry<String, Resource> me : res.entrySet()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (me.getKey().endsWith(".class")) { InputStream is = null; try { is = me.getValue().openInputStream(); byte[] bytes = new byte[8092]; int bytesRead = 0; while ((bytesRead = is.read(bytes, 0, 8092)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] classBytes = baos.toByteArray(); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(classBytes); byte[] digest = md.digest(); ClassReader cr = new ClassReader(classBytes); ClassInfo ca = new ClassInfo(pi, digest); cr.accept(ca, 0); for (int i = 0; i < ca.methods.size(); i++) { MethodNode mn = (MethodNode) ca.methods.get(i); // Ignore anything but public and protected methods if ((mn.access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC || (mn.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) { MethodInfo mi = new MethodInfo(mn, ca); ca.addPublicMethod(mi); } } for (int i = 0; i < ca.fields.size(); i++) { FieldNode mn = (FieldNode) ca.fields.get(i); // Ignore anything but public fields if ((mn.access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC || (mn.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) { FieldInfo mi = new FieldInfo(mn, ca); ca.addPublicField(mi); } } ret.add(ca); } catch (Exception e) { throw new RuntimeException(e); } } } return ret; } public Set<PackageInfo> getExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : packages.values()) { if (!pi.isExported()) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getPrivatePackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : packages.values()) { if (pi.isExported() || pi.isImported()) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getNewExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_NEW) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getModifiedExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_MODIFIED) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getRemovedExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_REMOVED) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getChangedExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() == PackageInfo.CHANGE_CODE_NONE) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getChangedPrivatePackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getPrivatePackages()) { if (pi.getChangeCode() == PackageInfo.CHANGE_CODE_NONE) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : packages.values()) { if (!pi.isImported()) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getNewImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_NEW) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getModifiedImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_MODIFIED) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getRemovedImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_REMOVED) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getChangedImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() == PackageInfo.CHANGE_CODE_NONE) { continue; } ret.add(pi); } return ret; } public static JarDiff createJarDiff(Project project, RepositoryPlugin baselineRepository, String bsn) { try { List<Builder> builders = project.getBuilder(null).getSubBuilders(); Builder builder = null; for (Builder b : builders) { if (bsn.equals(b.getBsn())) { builder = b; break; } } if (builder != null) { Jar jar = builder.build(); String bundleVersion = builder.getProperty(Constants.BUNDLE_VERSION); if (bundleVersion == null) { builder.setProperty(Constants.BUNDLE_VERSION, "0.0.0"); bundleVersion = "0.0.0"; } String unqualifiedVersion = removeVersionQualifier(bundleVersion); Version projectVersion = Version.parseVersion(unqualifiedVersion); String symbolicName = jar.getManifest().getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (symbolicName == null) { symbolicName = jar.getName().substring(0, jar.getName().lastIndexOf('-')); } Jar currentJar = null; VersionRange range = new VersionRange("[" + projectVersion.toString() + "," + projectVersion.toString() + "]"); try { if (baselineRepository != null) { File[] files = baselineRepository.get(symbolicName, range.toString()); if (files != null && files.length > 0) { currentJar = new Jar(files[0]); } } } catch (Exception e) { e.printStackTrace(); } JarDiff diff = new JarDiff(jar, currentJar); diff.setBaselineRepository(baselineRepository); diff.compare(); diff.calculatePackageVersions(); return diff; } } catch (Exception e1) { e1.printStackTrace(); } return null; } public void calculatePackageVersions() { int highestSeverity = PKG_SEVERITY_NONE; for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_MODIFIED) { continue; } String version = getVersionString(projectJar, pi.getPackageName()); if (version == null) { version = pi.getCurrentVersion(); } String mask; if (pi.getSeverity() > highestSeverity) { highestSeverity = pi.getSeverity(); } switch(pi.getSeverity()) { case PKG_SEVERITY_MINOR : mask = "=+0"; break; case PKG_SEVERITY_MAJOR : mask = "+00"; break; default: mask = null; } if (mask != null) { String suggestedVersion = _version(new String[] { "", mask, version}); pi.addSuggestedVersion(suggestedVersion); } else { pi.addSuggestedVersion(version); } } for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_REMOVED) { continue; } String mask; if (pi.getSeverity() > highestSeverity) { highestSeverity = pi.getSeverity(); } switch(pi.getSeverity()) { case PKG_SEVERITY_MINOR : mask = "=+0"; break; case PKG_SEVERITY_MAJOR : mask = "+00"; break; default: mask = null; } if (mask != null) { String suggestedVersion = "[" + _version(new String[] { "", mask, currentVersion}) + "]"; pi.addSuggestedVersion(suggestedVersion); } else { pi.addSuggestedVersion(currentVersion); } } String mask; switch(highestSeverity) { case PKG_SEVERITY_MINOR : mask = "=+0"; break; case PKG_SEVERITY_MAJOR : mask = "+00"; break; default: mask = "==+"; } String bundleVersion = currentVersion == null ? "0.0.0" : currentVersion; String unqualifiedVersion = removeVersionQualifier(bundleVersion); String suggestedVersion = _version(new String[] { "", mask, unqualifiedVersion}); suggestedVersions.add(suggestedVersion); if (suggestVersionOne(suggestedVersion)) { suggestedVersions.add("1.0.0"); } for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_NEW) { continue; } // Obey packageinfo if it exist String version = getVersionString(projectJar, pi.getPackageName()); if (version != null) { pi.addSuggestedVersion(version); if (suggestVersionOne(version)) { pi.addSuggestedVersion("1.0.0"); } } else { if (pi.getSuggestedVersion() == null || pi.getSuggestedVersion().length() == 0 || "0.0.0".equals(pi.getSuggestedVersion())) { pi.addSuggestedVersion(suggestedVersion); } if (suggestVersionOne(suggestedVersion)) { pi.addSuggestedVersion("1.0.0"); } } } } private boolean suggestVersionOne(String version) { aQute.libg.version.Version aQuteVersion = new aQute.libg.version.Version(version); if (aQuteVersion.compareTo(new aQute.libg.version.Version("1.0.0")) < 0) { return true; } return false; } // From aQute.libg.version.Macro _version. Without dependencies on project and properties private String _version(String[] args) { String mask = args[1]; aQute.libg.version.Version version = new aQute.libg.version.Version(args[2]); StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < mask.length(); i++) { char c = mask.charAt(i); String result = null; if (c != '~') { if (i == 3) { result = version.getQualifier(); } else if (Character.isDigit(c)) { // Handle masks like +00, =+0 result = String.valueOf(c); } else { int x = version.get(i); switch (c) { case '+': x++; break; case '-': x--; break; case '=': break; } result = Integer.toString(x); } if (result != null) { sb.append(del); del = "."; sb.append(result); } } } return sb.toString(); } private static String getVersionString(Jar jar, String packageName) { Resource resource = jar.getResource(getResourcePath(packageName, "packageinfo")); if (resource == null) { return null; } Properties packageInfo = new Properties(); InputStream is = null; try { is = resource.openInputStream(); packageInfo.load(is); } catch (Exception e) { throw new RuntimeException(e); } finally { if (is != null) { try {is.close();} catch (Exception e) {} } } String version = packageInfo.getProperty(VERSION); return version; } private static String getResourcePath(String packageName, String resourceName) { String s = packageName.replace('.', '/'); s += "/" + resourceName; return s; } public static String getSeverityText(int severity) { switch (severity) { case PKG_SEVERITY_MINOR : { return "Minor (Method or class added)"; } case PKG_SEVERITY_MAJOR : { return "Major (Class deleted, method changed or deleted)"; } default: { return ""; } } } public static void printDiff(JarDiff diff, PrintStream out) { out.println(); out.println("============================================"); out.println("Bundle " + diff.getSymbolicName() + ":"); out.println("============================================"); out.println("Version: " + diff.getCurrentVersion() + (diff.getSuggestedVersion() != null ? " -> Suggested Version: " + diff.getSuggestedVersion() : "")); if (diff.getModifiedExportedPackages().size() > 0) { out.println(); out.println("Modified Exported Packages:"); out.println("---------------------------"); for (PackageInfo pi : diff.getModifiedExportedPackages()) { out.println(pi.getPackageName() + " " + pi.getCurrentVersion() + " : " + getSeverityText(pi.getSeverity()) + (pi.getSuggestedVersion() != null ? " -> Suggested version: " + pi.getSuggestedVersion() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getModifiedImportedPackages().size() > 0) { out.println(); out.println("Modified Imported Packages:"); out.println("---------------------------"); for (PackageInfo pi : diff.getModifiedImportedPackages()) { out.println(pi.getPackageName() + " " + pi.getVersionRange() + " : " + getSeverityText(pi.getSeverity()) + (pi.getSuggestedVersionRange() != null ? " -> Suggested version range: " + pi.getSuggestedVersionRange() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getNewExportedPackages().size() > 0) { out.println(); out.println("Added Exported Packages:"); out.println("------------------------"); for (PackageInfo pi : diff.getNewExportedPackages()) { out.println(pi.getPackageName() + (pi.getSuggestedVersion() != null ? " -> Suggested version: " + pi.getSuggestedVersion() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getNewImportedPackages().size() > 0) { out.println(); out.println("Added Imported Packages:"); out.println("------------------------"); for (PackageInfo pi : diff.getNewImportedPackages()) { out.println(pi.getPackageName() + (pi.getSuggestedVersionRange() != null ? " -> Suggested version range: " + pi.getSuggestedVersionRange() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getRemovedExportedPackages().size() > 0) { out.println(); out.println("Deleted Exported Packages:"); out.println("--------------------------"); for (PackageInfo pi : diff.getRemovedExportedPackages()) { out.println(pi.getPackageName() + " " + pi.getCurrentVersion()); } } if (diff.getRemovedImportedPackages().size() > 0) { out.println(); out.println("Deleted Imported Packages:"); out.println("--------------------------"); for (PackageInfo pi : diff.getRemovedImportedPackages()) { out.println(pi.getPackageName() + " " + pi.getVersionRange()); } } } public String getSymbolicName() { return bundleSymbolicName; } public static String stripInstructions(String header) { if (header == null) { return null; } int idx = header.indexOf(';'); if (idx > -1) { return header.substring(0, idx); } return header; } public static String getAttribute(Manifest manifest, String attributeName) { if (manifest != null && attributeName != null) { return (String) manifest.getMainAttributes().get(new Attributes.Name(attributeName)); } return null; } public static String removeVersionQualifier(String version) { if (version == null) { return null; } // Remove qualifier String[] parts = version.split("\\."); StringBuilder sb = new StringBuilder(); String sep = ""; for (int i = 0; i < parts.length; i++) { if (i == 3) { break; } sb.append(sep); sb.append(parts[i]); sep = "."; } return sb.toString(); } public String getCurrentVersion() { return currentVersion; } public String getSuggestedVersion() { if (suggestedVersions.size() > 0) { return suggestedVersions.last(); } return null; } public TreeSet<String> getSuggestedVersions() { return suggestedVersions; } public String getSelectedVersion() { if (selectedVersion == null) { return getSuggestedVersion(); } return selectedVersion; } public void setSelectedVersion(String selectedVersion) { this.selectedVersion = selectedVersion; } public RepositoryPlugin getBaselineRepository() { return baselineRepository; } public void setBaselineRepository(RepositoryPlugin baselineRepository) { this.baselineRepository = baselineRepository; } public RepositoryPlugin getReleaseRepository() { return releaseRepository; } public void setReleaseRepository(RepositoryPlugin releaseRepository) { this.releaseRepository = releaseRepository; } }
false
true
public void compare() throws Exception { Manifest projectManifest = projectJar.getManifest(); Parameters projectExportedPackages = new Parameters(getAttribute(projectManifest, Constants.EXPORT_PACKAGE)); Parameters projectImportedPackages = new Parameters(getAttribute(projectManifest, Constants.IMPORT_PACKAGE)); bundleSymbolicName = stripInstructions(getAttribute(projectManifest, Constants.BUNDLE_SYMBOLICNAME)); currentVersion = removeVersionQualifier(getAttribute(projectManifest, Constants.BUNDLE_VERSION)); // This is the version from the .bnd file Parameters previousExportedPackages; Parameters previousImportedPackages; Manifest previousManifest = null; if (previousJar != null) { previousManifest = previousJar.getManifest(); previousExportedPackages = new Parameters(getAttribute(previousManifest, Constants.EXPORT_PACKAGE)); previousImportedPackages = new Parameters(getAttribute(previousManifest, Constants.IMPORT_PACKAGE)); // If no version in projectJar use previous version if (currentVersion == null) { currentVersion = removeVersionQualifier(getAttribute(previousManifest, Constants.BUNDLE_VERSION)); } } else { previousExportedPackages = new Parameters(); // empty previousImportedPackages = new Parameters(); // empty } String prevName = stripInstructions(getAttribute(previousManifest, Constants.BUNDLE_SYMBOLICNAME)); if (bundleSymbolicName != null && prevName != null && !bundleSymbolicName.equals(prevName)) { throw new IllegalArgumentException(Constants.BUNDLE_SYMBOLICNAME + " must be equal"); } // Private packages if (previousJar != null) { for (String packageName : projectJar.getPackages()) { if (!projectExportedPackages.containsKey(packageName)) { PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); } Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, null); if (projectClasses.size() == 0) { continue; } if (!packages.containsKey(packageName)) { packages.put(packageName, pi); } Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, null); Set<ClassInfo> cis = pi.getClasses(); for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } cis.add(ci); if (prevCi != null && !Arrays.equals(ci.getSHA1(), prevCi.getSHA1())) { ci.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } if (prevCi == null) { ci.setChangeCode(ClassInfo.CHANGE_CODE_NEW); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } } if (previousClasses != null) { for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { cis.add(prevCi); prevCi.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); } } } } } } for (Entry<String, Attrs> entry : projectImportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); Map<String, String> packageMap = entry.getValue(); String version = packageMap.get(VERSION); VersionRange projectVersion = null; if (version != null) { projectVersion = new VersionRange(version); pi.setSuggestedVersionRange(projectVersion.toString()); } if (previousImportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); version = prevPackageMap.get(VERSION); VersionRange previousVersion = null; if (version != null) { previousVersion = new VersionRange(version); } // No change, no versions if (projectVersion == null && previousVersion == null) { continue; } // No change if (projectVersion != null && previousVersion != null) { if (projectVersion.getHigh().equals(previousVersion.getHigh()) && projectVersion.getLow().equals(previousVersion.getLow())) { pi.setVersionRange(previousVersion.toString()); continue; } pi.setSeverity(PKG_SEVERITY_MINOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (projectVersion != null) { pi.setSeverity(PKG_SEVERITY_MAJOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (previousVersion != null) { pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); } } } for (String packageName : previousImportedPackages.keySet()) { if (!projectImportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); pi.setVersionRange(previousVersion); } } for (String packageName : projectExportedPackages.keySet()) { // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); Map<String, String> packageMap = projectExportedPackages.get(packageName); String packageVersion = removeVersionQualifier(packageMap.get(VERSION)); Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, packageVersion); Set<ClassInfo> cis = pi.getClasses(); String previousVersion = null; Set<ClassInfo> previousClasses = null; if (previousExportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); previousVersion = prevPackageMap.get(VERSION); previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); } for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } int severity = getModificationSeverity(ci, prevCi); cis.add(ci); if (severity > PKG_SEVERITY_NONE) { // New or modified class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } } } if (pi.getSeverity() > PKG_SEVERITY_NONE) { if (previousClasses == null) { // New package pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.addSuggestedVersion(packageVersion); } else { // Modified package pi.setCurrentVersion(previousVersion); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } if (pi.getSeverity() == PKG_SEVERITY_NONE) { if (previousClasses != null && previousVersion == null) { // No change, but version missing on package pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_VERSION_MISSING); pi.addSuggestedVersion(getCurrentVersion()); } } if (previousClasses != null) { pi.setCurrentVersion(previousVersion); for (ClassInfo prevCi : previousClasses) { if (projectClasses != null && !projectClasses.contains(prevCi)) { int severity = getModificationSeverity(null, prevCi); cis.add(prevCi); if (severity > PKG_SEVERITY_NONE) { // Removed class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } } } } for (String packageName : previousExportedPackages.keySet()) { if (!projectExportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); pi.setClasses(previousClasses); pi.setSeverity(PKG_SEVERITY_MAJOR); for (ClassInfo prevCi : previousClasses) { // Removed class getModificationSeverity(null, prevCi); } pi.setCurrentVersion(previousVersion); } } }
public void compare() throws Exception { Manifest projectManifest = projectJar.getManifest(); Parameters projectExportedPackages = new Parameters(getAttribute(projectManifest, Constants.EXPORT_PACKAGE)); Parameters projectImportedPackages = new Parameters(getAttribute(projectManifest, Constants.IMPORT_PACKAGE)); bundleSymbolicName = stripInstructions(getAttribute(projectManifest, Constants.BUNDLE_SYMBOLICNAME)); currentVersion = removeVersionQualifier(getAttribute(projectManifest, Constants.BUNDLE_VERSION)); // This is the version from the .bnd file Parameters previousExportedPackages; Parameters previousImportedPackages; Manifest previousManifest = null; if (previousJar != null) { previousManifest = previousJar.getManifest(); previousExportedPackages = new Parameters(getAttribute(previousManifest, Constants.EXPORT_PACKAGE)); previousImportedPackages = new Parameters(getAttribute(previousManifest, Constants.IMPORT_PACKAGE)); // If no version in projectJar use previous version if (currentVersion == null) { currentVersion = removeVersionQualifier(getAttribute(previousManifest, Constants.BUNDLE_VERSION)); } } else { previousExportedPackages = new Parameters(); // empty previousImportedPackages = new Parameters(); // empty } String prevName = stripInstructions(getAttribute(previousManifest, Constants.BUNDLE_SYMBOLICNAME)); if (bundleSymbolicName != null && prevName != null && !bundleSymbolicName.equals(prevName)) { throw new IllegalArgumentException(Constants.BUNDLE_SYMBOLICNAME + " must be equal"); } // Private packages if (previousJar != null) { for (String packageName : projectJar.getPackages()) { if (!projectExportedPackages.containsKey(packageName)) { PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); } Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, null); if (projectClasses.size() == 0) { continue; } if (!packages.containsKey(packageName)) { packages.put(packageName, pi); } Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, null); Set<ClassInfo> cis = pi.getClasses(); for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } cis.add(ci); if (prevCi != null && !Arrays.equals(ci.getSHA1(), prevCi.getSHA1())) { ci.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } if (prevCi == null) { ci.setChangeCode(ClassInfo.CHANGE_CODE_NEW); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } } if (previousClasses != null) { for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { cis.add(prevCi); prevCi.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); } } } } } } for (Entry<String, Attrs> entry : projectImportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); Map<String, String> packageMap = entry.getValue(); String version = packageMap.get(VERSION); VersionRange projectVersion = null; if (version != null) { projectVersion = new VersionRange(version); pi.setSuggestedVersionRange(projectVersion.toString()); } if (previousImportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); version = prevPackageMap.get(VERSION); VersionRange previousVersion = null; if (version != null) { previousVersion = new VersionRange(version); } // No change, no versions if (projectVersion == null && previousVersion == null) { continue; } // No change if (projectVersion != null && previousVersion != null) { if (projectVersion.getHigh().equals(previousVersion.getHigh()) && projectVersion.getLow().equals(previousVersion.getLow())) { pi.setVersionRange(previousVersion.toString()); continue; } pi.setSeverity(PKG_SEVERITY_MINOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (projectVersion != null) { pi.setSeverity(PKG_SEVERITY_MAJOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (previousVersion != null) { pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); } } } for (Entry<String, Attrs> entry : previousImportedPackages.entrySet()) { String packageName = entry.getKey(); if (!projectImportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); pi.setVersionRange(previousVersion); } } for (Entry<String, Attrs> entry : projectExportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); Map<String, String> packageMap = entry.getValue(); String packageVersion = removeVersionQualifier(packageMap.get(VERSION)); Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, packageVersion); Set<ClassInfo> cis = pi.getClasses(); String previousVersion = null; Set<ClassInfo> previousClasses = null; if (previousExportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); previousVersion = prevPackageMap.get(VERSION); previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); } for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } int severity = getModificationSeverity(ci, prevCi); cis.add(ci); if (severity > PKG_SEVERITY_NONE) { // New or modified class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } } } if (pi.getSeverity() > PKG_SEVERITY_NONE) { if (previousClasses == null) { // New package pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.addSuggestedVersion(packageVersion); } else { // Modified package pi.setCurrentVersion(previousVersion); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } if (pi.getSeverity() == PKG_SEVERITY_NONE) { if (previousClasses != null && previousVersion == null) { // No change, but version missing on package pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_VERSION_MISSING); pi.addSuggestedVersion(getCurrentVersion()); } } if (previousClasses != null) { pi.setCurrentVersion(previousVersion); for (ClassInfo prevCi : previousClasses) { if (projectClasses != null && !projectClasses.contains(prevCi)) { int severity = getModificationSeverity(null, prevCi); cis.add(prevCi); if (severity > PKG_SEVERITY_NONE) { // Removed class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } } } } for (String packageName : previousExportedPackages.keySet()) { if (!projectExportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); pi.setClasses(previousClasses); pi.setSeverity(PKG_SEVERITY_MAJOR); for (ClassInfo prevCi : previousClasses) { // Removed class getModificationSeverity(null, prevCi); } pi.setCurrentVersion(previousVersion); } } }
diff --git a/biojava3-structure/src/main/java/org/biojava/bio/structure/DBRef.java b/biojava3-structure/src/main/java/org/biojava/bio/structure/DBRef.java index 6e4fb04f3..2b7326e5a 100644 --- a/biojava3-structure/src/main/java/org/biojava/bio/structure/DBRef.java +++ b/biojava3-structure/src/main/java/org/biojava/bio/structure/DBRef.java @@ -1,433 +1,434 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on Sep 3, 2007 * */ package org.biojava.bio.structure; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Formatter; import java.util.Locale; /** A class to represent database cross references. This is just a simple bean that contains the infor from one * DBREF line * * @author Andreas Prlic * @since 4:56:14 PM * @version %I% %G% */ public class DBRef implements PDBRecord, Serializable{ /** * */ private static final long serialVersionUID = -1050178577542224379L; Structure parent; String idCode; Character chainId; int seqbegin; char insertBegin; int seqEnd; char insertEnd; String database; String dbAccession; String dbIdCode; int dbSeqBegin; char idbnsBegin; int dbSeqEnd; char idbnsEnd; private Long id; public DBRef() { insertBegin = ' '; insertEnd = ' '; idbnsBegin = ' '; idbnsEnd = ' '; } /** Get the ID used by Hibernate. * * @return the ID used by Hibernate * @see #setId(Long) */ public Long getId() { return id; } /** Set the ID used by Hibernate. * * @param id the id assigned by Hibernate * @see #getId() */ public void setId(Long id) { this.id = id; } /** Set the structure object that this DBRef relates to. * * @param s a structure object * @see #getParent() */ public void setParent(Structure s){ parent = s; } /** Get the structure object that this DBRef relates to. * * @return s a structure object * @see #setParent(Structure) */ public Structure getParent(){ return parent; } /** Convert the DBRef object to a DBREF record as it is used in PDB files * * @return a PDB - DBREF formatted line */ public String toPDB(){ StringBuffer buf = new StringBuffer(); toPDB(buf); return buf.toString(); } /** Append the PDB representation of this DBRef to the provided StringBuffer * * @param buf the StringBuffer to write to. */ public void toPDB(StringBuffer buf){ StringBuilder build = new StringBuilder(); Formatter form = new Formatter(build,Locale.UK); // DBREF 3ETA A 990 1295 UNP P06213 INSR_HUMAN 1017 1322 // DBREF 3EH2 A 2 767 UNP P53992 SC24C_HUMAN 329 1094 // DBREF 3EH2 A 2 767 UNP P53992 SC24C_HUMAN 329 1094 // DBREF 3ETA A 990 1295 UNP P06213 INSR_HUMAN 1017 1322 form.format("DBREF %4s %1s %4d%1s %4d%1s %-6s %-8s %-12s%6d%1c%6d%1c", idCode, chainId,seqbegin,insertBegin,seqEnd,insertEnd, database,dbAccession,dbIdCode, dbSeqBegin,idbnsBegin,dbSeqEnd,idbnsEnd ); buf.append(build.toString().trim()); } /** String representation of a DBRef. * @return a String */ public String toString(){ StringBuffer buf = new StringBuffer(); try { - Class c = Class.forName("org.biojava.bio.structure.DBRef"); + @SuppressWarnings("rawtypes") + Class c = Class.forName("org.biojava.bio.structure.DBRef"); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); if ( name.substring(0,3).equals("get")) { if (name.equals("getClass")) continue; Object o = m.invoke(this, new Object[]{}); if ( o != null){ buf.append(name.substring(3,name.length())); buf.append(": " + o + " "); } } } } catch (Exception e){ e.printStackTrace(); } return buf.toString(); } /** get the idCode for this entry * * @return the idCode * @see #setIdCode(String) */ public String getIdCode() { return idCode; } /** Set the idCode for this entry. * * @param idCode the idCode for this entry * @see #getIdCode() */ public void setIdCode(String idCode) { this.idCode = idCode; } /** The chain ID of the corresponding chain. * * @return chainId the ID of the corresponding chain. * @see #setChainId(Character) */ public Character getChainId() { return chainId; } /** The chain ID of the corresponding chain. * * @param chainId the ID of the corresponding chain * @see #getChainId() */ public void setChainId(Character chainId) { this.chainId = chainId; } /** The database of the db-ref. * uses the abbreviation as provided in the PDB files: * *<pre> Database name database (code in columns 27 - 32) ---------------------------------------------------------- GenBank GB Protein Data Bank PDB Protein Identification Resource PIR SWISS-PROT SWS TREMBL TREMBL UNIPROT UNP </pre> * @return name of database of this DBRef * @see #setDatabase(String) */ public String getDatabase() { return database; } /** Specifies the database value. * * @param database the database * @see #getDatabase() */ public void setDatabase(String database) { this.database = database; } /** Sequence database accession code. * @return the dbAccession * @see #setDbAccession(String) * */ public String getDbAccession() { return dbAccession; } /** Sequence database accession code. * @param dbAccession the dbAccession * @see #getDbAccession() * */ public void setDbAccession(String dbAccession) { this.dbAccession = dbAccession; } /** Sequence database identification code. * * @return the dbIdCode * @see #setDbIdCode(String) */ public String getDbIdCode() { return dbIdCode; } /** Sequence database identification code. * * @param dbIdCode identification code * @see #getDbIdCode() */ public void setDbIdCode(String dbIdCode) { this.dbIdCode = dbIdCode; } /** Initial sequence number of the database seqment. * @return position * @see #setDbSeqBegin(int) */ public int getDbSeqBegin() { return dbSeqBegin; } /** Initial sequence number of the database seqment. * @param dbSeqBegin a sequence position * @see #getDbSeqBegin() * */ public void setDbSeqBegin(int dbSeqBegin) { this.dbSeqBegin = dbSeqBegin; } /** Ending sequence position of the database segment. * @return dbSeqEnd * @see #setDbSeqEnd(int) */ public int getDbSeqEnd() { return dbSeqEnd; } /** The begin of the sequence position in the database * * @param dbSeqEnd sequence position * @see #getDbSeqEnd() */ public void setDbSeqEnd(int dbSeqEnd) { this.dbSeqEnd = dbSeqEnd; } /** Insertion code of initial residue of the segment, if PDB is the reference. * @return idbnsBegin isnertion code * @see #setIdbnsBegin(char) * */ public char getIdbnsBegin() { return idbnsBegin; } /** Insertion code of initial residue of the segment, if PDB is the reference. * @param idbnsBegin insertion code * @see #getIdbnsBegin() * */ public void setIdbnsBegin(char idbnsBegin) { this.idbnsBegin = idbnsBegin; } /** Insertion code of the ending residue of the segment, if PDB is the reference. * @return idbnsEnd insertion code * @see #setIdbnsEnd(char) */ public char getIdbnsEnd() { return idbnsEnd; } /** Insertion code of the ending residue of the segment, if PDB is the reference. * @param idbnsEnd the insertion code * @see #setIdbnsEnd(char) */ public void setIdbnsEnd(char idbnsEnd) { this.idbnsEnd = idbnsEnd; } /** Initial insertion code of the PDB sequence segment. * * @return insertBegin * @see #setInsertBegin(char) */ public char getInsertBegin() { return insertBegin; } /** Initial insertion code of the PDB sequence segment. * * @param insertBegin * @see #getInsertBegin() */ public void setInsertBegin(char insertBegin) { this.insertBegin = insertBegin; } /** Ending insertion code of the PDB sequence segment. * * @return insertEnd insertion code * @see #setInsertEnd(char) */ public char getInsertEnd() { return insertEnd; } /** Ending insertion code of the PDB sequence segment. * * @param insertEnd insertEnd * @see #getInsertEnd() * */ public void setInsertEnd(char insertEnd) { this.insertEnd = insertEnd; } /** Initial sequence number of the PDB sequence segment. * * @return start seq. position * @see #setSeqBegin */ public int getSeqBegin() { return seqbegin; } /** Initial sequence number of the PDB sequence segment. * * @param seqbegin start seq. position * @see #getSeqBegin() */ public void setSeqBegin(int seqbegin) { this.seqbegin = seqbegin; } /**Ending sequence number of the PDB sequence segment. * * @return sequence end position * @see #getSeqEnd() */ public int getSeqEnd() { return seqEnd; } /**Ending sequence number of the PDB sequence segment. * * @param seqEnd sequence end position * @see #setSeqEnd(int) * */ public void setSeqEnd(int seqEnd) { this.seqEnd = seqEnd; } }
true
true
public String toString(){ StringBuffer buf = new StringBuffer(); try { Class c = Class.forName("org.biojava.bio.structure.DBRef"); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); if ( name.substring(0,3).equals("get")) { if (name.equals("getClass")) continue; Object o = m.invoke(this, new Object[]{}); if ( o != null){ buf.append(name.substring(3,name.length())); buf.append(": " + o + " "); } } } } catch (Exception e){ e.printStackTrace(); } return buf.toString(); }
public String toString(){ StringBuffer buf = new StringBuffer(); try { @SuppressWarnings("rawtypes") Class c = Class.forName("org.biojava.bio.structure.DBRef"); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); if ( name.substring(0,3).equals("get")) { if (name.equals("getClass")) continue; Object o = m.invoke(this, new Object[]{}); if ( o != null){ buf.append(name.substring(3,name.length())); buf.append(": " + o + " "); } } } } catch (Exception e){ e.printStackTrace(); } return buf.toString(); }
diff --git a/jing/chem/Therfit.java b/jing/chem/Therfit.java index 2df94503..ea6940d9 100644 --- a/jing/chem/Therfit.java +++ b/jing/chem/Therfit.java @@ -1,269 +1,269 @@ //!******************************************************************************** //! //! RMG: Reaction Mechanism Generator //! //! Copyright: Jing Song, MIT, 2002, all rights reserved //! //! Author's Contact: [email protected] //! //! Restrictions: //! (1) RMG is only for non-commercial distribution; commercial usage //! must require other written permission. //! (2) Redistributions of RMG must retain the above copyright //! notice, this list of conditions and the following disclaimer. //! (3) The end-user documentation included with the redistribution, //! if any, must include the following acknowledgment: //! "This product includes software RMG developed by Jing Song, MIT." //! Alternately, this acknowledgment may appear in the software itself, //! if and wherever such third-party acknowledgments normally appear. //! //! RMG IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED //! WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES //! OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //! DISCLAIMED. IN NO EVENT SHALL JING SONG BE LIABLE FOR //! ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR //! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT //! OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; //! OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF //! LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //! (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF //! THE USE OF RMG, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //! //!****************************************************************************** package jing.chem; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import jing.chemParser.ChemParser; import jing.mathTool.MathTool; /** * Contains data members and methods for interacting with THERFIT, a module that * models the degrees of freedom of a molecule using three frequency-degeneracy * pairs developed by Chang, Bozzelli, and Dean. * This was the original method of modeling the degrees of freedom, but has * since been made obsolete in favor of a more general model contained in the * class SpectroscopicData. * <p> * For more information on THERFIT, see the following reference: * <p> * A. Y. Chang, J. W. Bozzelli, and A. M. Dean. "Kinetic Analysis of Complex * Chemical Activation and Unimolecular Dissociation Reactions using QRRK * Theory and the Modified Strong Collision Approximation." Z. Phys. Chem * 214 (11), p. 1533-1568 (2000). * * @author jwallen */ public class Therfit { //## operation generateThreeFrequencyModel() public static ThreeFrequencyModel generateThreeFrequencyModel(Species species) { if (species.isTriatomicOrSmaller()) { System.out.println("Warning: Attempted to fit three frequency model to triatomic or smaller."); return null; } //String directory = System.getProperty("RMG.workingDirectory"); String mode = "HOE"; // use Harmonic Oscillator Eqn to calc psuedo-freqs String dir = "therfit"; // prepare therfit input file and execute system call boolean error = callTherfit(species, dir, mode); if (error) { System.out.println("Warning: Error detected in THERFIT execution. Three frequency model not fitted."); return null; } double [] degeneracy = new double [3]; double [] frequency = new double [3]; try { String therfit_output = dir+"/fort.25"; FileReader in = new FileReader(therfit_output); BufferedReader data = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(data); if (!line.startsWith(species.getChemkinName())) { System.out.println("Wrong output from therfit!"); System.exit(0); } int index = 0; line = ChemParser.readMeaningfulLine(data); while (line != null) { line = line.trim(); if (line.startsWith("VIBRATION")) { if (index > 2) break; StringTokenizer token = new StringTokenizer(line); String temp = token.nextToken(); temp = token.nextToken(); temp = token.nextToken(); temp = token.nextToken(); String deg = token.nextToken(); temp = token.nextToken(); temp = token.nextToken(); String freq = token.nextToken(); degeneracy[index] = Double.parseDouble(deg); frequency[index] = Double.parseDouble(freq); index++; } line = ChemParser.readMeaningfulLine(data); } in.close(); } catch (Exception e) { System.out.println("Wrong output fort.25 from therfit!"); System.exit(0); } // create threeFrequencyModel for this species return new ThreeFrequencyModel(frequency, degeneracy); } private static boolean callTherfit(Species species, String p_directory, String p_mode) { if (p_directory == null || p_mode == null) throw new NullPointerException(); String workingDirectory = System.getProperty("RMG.workingDirectory"); // write therfit input file String result = p_mode.toUpperCase() + '\n'; result += species.getChemkinName() + '\n'; ThermoData td = species.getThermoData(); result += MathTool.formatDouble(td.getH298(), 8, 2) + '\n'; result += MathTool.formatDouble(td.getS298(), 8, 2) + '\n'; result += MathTool.formatDouble(td.getCp300(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp400(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp500(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp600(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp800(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp1000(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp1500(), 7, 3) + '\n'; ChemGraph cg = species.getChemGraph(); result += "C\n"; result += MathTool.formatInteger(cg.getCarbonNumber(),3,"R") + '\n'; result += "H\n"; result += MathTool.formatInteger(cg.getHydrogenNumber(),3,"R") + '\n'; int oNum = cg.getOxygenNumber(); if (oNum == 0) { result += "0\n0\n"; } else { result += "O\n"; result += MathTool.formatInteger(oNum,3,"R") + '\n'; } result += "0\n0\n"; result += "G\n"; result += Integer.toString(species.getInternalRotor()) + '\n'; // finished writing text for input file, now save result to fort.1 String therfit_input_name = null; File therfit_input = null; try { // prepare therfit input file, "fort.1" is the input file name therfit_input_name = p_directory+"/fort.1";//p_directory+"/software/therfit/fort.1"; therfit_input = new File(therfit_input_name); FileWriter fw = new FileWriter(therfit_input); fw.write(result); fw.close(); } catch (IOException e) { System.out.println("Wrong input file for therfit!"); System.exit(0); } // call therfit boolean error = false; try { // system call for therfit String[] command = {workingDirectory + "/software/therfit/therfit.exe"}; File runningDir = new File(p_directory );//+ "/therfit");// "/software/therfit"); Process therfit = Runtime.getRuntime().exec(command, null, runningDir); InputStream is = therfit.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) { //System.out.println(line); line = line.trim(); if (!line.startsWith("*** THRFIT Job Complete")) { String speName = species.getName(); System.out.println("therfit error for species: " + speName+"\n"+species.toString()); - System.out.println("was expecting ' *** THRFIT Job Complete...' and instead got '" + line +"'."); + System.out.println("Was expecting '*** THRFIT Job Complete...' and instead got '" + line +"'."); File newfile = new File(therfit_input_name+"."+speName); therfit_input.renameTo(newfile); error = true; } } int exitValue = therfit.waitFor(); br.close(); isr.close(); } catch (Exception e) { System.out.println("Error in run therfit!"); System.exit(0); } // return error = true, if there was a problem return error; //#] } //## operation generateNASAThermoData() public static NASAThermoData generateNASAThermoData(Species species) { ///#[ operation generateNASAThermoData() // get working directory //String dir = System.getProperty("RMG.workingDirectory"); String mode = "WILHOI"; // use Wilhoit polynomial to extrapolate Cp String dir = "therfit"; // prepare therfit input file and execute system call boolean error = callTherfit(species, dir, mode); // parse output from therfit, "fort.25" is the output file name if (error) { System.out.println("Error in generating NASA thermodata!"); System.exit(0); } NASAThermoData nasaThermoData = null; try { String therfit_nasa_output = dir+"/fort.54"; FileReader in = new FileReader(therfit_nasa_output); BufferedReader data = new BufferedReader(in); String line = data.readLine(); String nasaString = ""; while (line != null) { nasaString += line + "\n"; line = data.readLine(); } nasaThermoData = new NASAThermoData(nasaString); } catch (Exception e) { System.out.println("Wrong output from therfit!"); System.exit(0); } return nasaThermoData; //#] } }
true
true
private static boolean callTherfit(Species species, String p_directory, String p_mode) { if (p_directory == null || p_mode == null) throw new NullPointerException(); String workingDirectory = System.getProperty("RMG.workingDirectory"); // write therfit input file String result = p_mode.toUpperCase() + '\n'; result += species.getChemkinName() + '\n'; ThermoData td = species.getThermoData(); result += MathTool.formatDouble(td.getH298(), 8, 2) + '\n'; result += MathTool.formatDouble(td.getS298(), 8, 2) + '\n'; result += MathTool.formatDouble(td.getCp300(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp400(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp500(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp600(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp800(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp1000(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp1500(), 7, 3) + '\n'; ChemGraph cg = species.getChemGraph(); result += "C\n"; result += MathTool.formatInteger(cg.getCarbonNumber(),3,"R") + '\n'; result += "H\n"; result += MathTool.formatInteger(cg.getHydrogenNumber(),3,"R") + '\n'; int oNum = cg.getOxygenNumber(); if (oNum == 0) { result += "0\n0\n"; } else { result += "O\n"; result += MathTool.formatInteger(oNum,3,"R") + '\n'; } result += "0\n0\n"; result += "G\n"; result += Integer.toString(species.getInternalRotor()) + '\n'; // finished writing text for input file, now save result to fort.1 String therfit_input_name = null; File therfit_input = null; try { // prepare therfit input file, "fort.1" is the input file name therfit_input_name = p_directory+"/fort.1";//p_directory+"/software/therfit/fort.1"; therfit_input = new File(therfit_input_name); FileWriter fw = new FileWriter(therfit_input); fw.write(result); fw.close(); } catch (IOException e) { System.out.println("Wrong input file for therfit!"); System.exit(0); } // call therfit boolean error = false; try { // system call for therfit String[] command = {workingDirectory + "/software/therfit/therfit.exe"}; File runningDir = new File(p_directory );//+ "/therfit");// "/software/therfit"); Process therfit = Runtime.getRuntime().exec(command, null, runningDir); InputStream is = therfit.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) { //System.out.println(line); line = line.trim(); if (!line.startsWith("*** THRFIT Job Complete")) { String speName = species.getName(); System.out.println("therfit error for species: " + speName+"\n"+species.toString()); System.out.println("was expecting ' *** THRFIT Job Complete...' and instead got '" + line +"'."); File newfile = new File(therfit_input_name+"."+speName); therfit_input.renameTo(newfile); error = true; } } int exitValue = therfit.waitFor(); br.close(); isr.close(); } catch (Exception e) { System.out.println("Error in run therfit!"); System.exit(0); } // return error = true, if there was a problem return error; //#] }
private static boolean callTherfit(Species species, String p_directory, String p_mode) { if (p_directory == null || p_mode == null) throw new NullPointerException(); String workingDirectory = System.getProperty("RMG.workingDirectory"); // write therfit input file String result = p_mode.toUpperCase() + '\n'; result += species.getChemkinName() + '\n'; ThermoData td = species.getThermoData(); result += MathTool.formatDouble(td.getH298(), 8, 2) + '\n'; result += MathTool.formatDouble(td.getS298(), 8, 2) + '\n'; result += MathTool.formatDouble(td.getCp300(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp400(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp500(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp600(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp800(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp1000(), 7, 3) + '\n'; result += MathTool.formatDouble(td.getCp1500(), 7, 3) + '\n'; ChemGraph cg = species.getChemGraph(); result += "C\n"; result += MathTool.formatInteger(cg.getCarbonNumber(),3,"R") + '\n'; result += "H\n"; result += MathTool.formatInteger(cg.getHydrogenNumber(),3,"R") + '\n'; int oNum = cg.getOxygenNumber(); if (oNum == 0) { result += "0\n0\n"; } else { result += "O\n"; result += MathTool.formatInteger(oNum,3,"R") + '\n'; } result += "0\n0\n"; result += "G\n"; result += Integer.toString(species.getInternalRotor()) + '\n'; // finished writing text for input file, now save result to fort.1 String therfit_input_name = null; File therfit_input = null; try { // prepare therfit input file, "fort.1" is the input file name therfit_input_name = p_directory+"/fort.1";//p_directory+"/software/therfit/fort.1"; therfit_input = new File(therfit_input_name); FileWriter fw = new FileWriter(therfit_input); fw.write(result); fw.close(); } catch (IOException e) { System.out.println("Wrong input file for therfit!"); System.exit(0); } // call therfit boolean error = false; try { // system call for therfit String[] command = {workingDirectory + "/software/therfit/therfit.exe"}; File runningDir = new File(p_directory );//+ "/therfit");// "/software/therfit"); Process therfit = Runtime.getRuntime().exec(command, null, runningDir); InputStream is = therfit.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) { //System.out.println(line); line = line.trim(); if (!line.startsWith("*** THRFIT Job Complete")) { String speName = species.getName(); System.out.println("therfit error for species: " + speName+"\n"+species.toString()); System.out.println("Was expecting '*** THRFIT Job Complete...' and instead got '" + line +"'."); File newfile = new File(therfit_input_name+"."+speName); therfit_input.renameTo(newfile); error = true; } } int exitValue = therfit.waitFor(); br.close(); isr.close(); } catch (Exception e) { System.out.println("Error in run therfit!"); System.exit(0); } // return error = true, if there was a problem return error; //#] }
diff --git a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/DatLoader.java b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/DatLoader.java index aa7fd56f3..037be7358 100644 --- a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/DatLoader.java +++ b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/DatLoader.java @@ -1,439 +1,439 @@ /* * Copyright 2011 Diamond Light Source Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.diamond.scisoft.analysis.io; import gda.analysis.io.ScanFileHolderException; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.ILazyDataset; import uk.ac.diamond.scisoft.analysis.monitor.IMonitor; /** * This class loads a dat data files where: * * 0. The file is ascii/utf-8 * 1. The header is a section at the start and starting with a # * 2. The footer is a section at the end and starting with a # * 3. The data lines consist only of numbers separated by whitespace, 2 columns or more. * 4. The names of the data sets are defined in the last line of the header. They are separated * by white space but if commas are used as well these will be stripped from the names. * A single space without a comma is not included as data set names may contain spaces. * * * Example: (see also unit tests) * * # DIAMOND LIGHT SOURCE # Instrument: I20-XAS Date: Mon, 19 Jul 2010 13:54:16 BST # Ring energy: 56.66749 GeV # Initial ring current: 72.23874 mA # Filling mode: 50.05388 # Wiggler gap selected: 0.00000 mm # # Primary slits: vertical gap= 0.00000 mm; horizontal gap= 0.00000 mm; vertical offset= 0.00000 mm; horizontal offset= 0.00000 mm # Secondary slits: vertical gap= 0.00000 mm; horizontal gap= 0.00000 mm; vertical offset= 0.00000 mm; horizontal offset= 0.00000 mm # Experimental slits: vertical gap= 0.00000 mm; horizontal gap= 0.00000 mm; vertical offset= 0.00000 mm; horizontal offset= 0.00000 mm # # Optic Hutch Mirrors Coating: 77.14589850662986 # Monochromator crystal cut: 84.35454401226806 # Incident angle for Harmonic Rejection Mirrors: 90.46 mrad # Harmonic rejection mirrors coating: 57.76820936133954 # # Ascii output file name: 'FeKedge_1_15.dat' # Nexus output file: '/scratch/users/data/2010/cm1903-4/Experiment_1/nexus/FeKedge_1_15.nxs' # The XML files, ScanParameters, SampleParameters, DetectorParameters, OutputParameters # are stored in the nexus file. # # Sample name: Please set a sample name... # Please add a description... # # Detector: Ge (XSPRESS) # # Dark current intensity (Hz): I0 150 It 230 Iref 135 # Dark current has been automatically removed from counts in main scan (I0,It,Iref) # # Energy I0 It Iref ln(I0/It) ln(It/Iref) FF FF/I0 Integration Time Element 0 Element 1 Element 2 Element 3 Element 4 Element 5 Element 6 Element 7 Element 8 Element 9 Element 10 Element 11 Element 12 Element 13 Element 14 Element 15 Element 16 Element 17 Element 18 Element 19 Element 20 Element 21 Element 22 Element 23 Element 24 Element 25 Element 26 Element 27 Element 28 Element 29 Element 30 Element 31 Element 32 Element 33 Element 34 Element 35 Element 36 Element 37 Element 38 Element 39 Element 40 Element 41 Element 42 Element 43 Element 44 Element 45 Element 46 Element 47 Element 48 Element 49 Element 50 Element 51 Element 52 Element 53 Element 54 Element 55 Element 56 Element 57 Element 58 Element 59 Element 60 Element 61 Element 62 Element 63 6912.0000 134878.0 2040284.0 295077.5 -2.716 1.934 10270610.99 10555624.6977 0.5000 -12522.13 -39259.72 240563.80 -18371.26 -23133.33 -26645.71 -8850.84 -32861.71 564452.59 478611.82 226456.06 168938.08 102221.88 -1823.24 -4091.32 -47298.75 726493.32 -52899.04 -32855.20 593012.73 199522.96 202352.74 185485.28 38464.16 -65122.61 -10684.71 -1507.41 423263.14 -4528.40 350455.46 -21235.13 -75253.78 -4209.37 165226.15 35165.22 -78922.48 -10288.62 -77462.30 -6722.40 354852.04 418246.19 -30032.34 -75643.93 -3506.16 92636.17 -41200.23 301540.78 460221.12 989244.43 102729.58 23667.98 327453.07 -42080.14 102140.45 -22449.90 407986.95 601299.66 573668.62 157472.43 551740.78 258796.50 117267.94 87473.48 512949.58 6917.0000 111091.0 1680648.0 295086.5 -2.717 1.740 8069498.24 9446808.2869 0.5000 421871.76 -17924.10 -23503.70 -18711.85 -21437.16 97863.36 -7528.52 90575.20 562247.53 9261.75 -10753.65 -6481.09 511078.54 -2886.82 188671.06 -76532.81 144969.57 591234.90 -77537.48 -13101.69 78814.69 529177.36 573390.24 992058.81 169218.60 -24463.02 -76107.58 144951.34 492050.24 -6852.50 -61568.14 -19371.64 268265.42 -43395.58 -50644.15 442379.96 -25656.06 -20971.66 124481.27 30026.80 -9798.52 -44064.34 62571.57 629673.44 440609.56 274190.73 -19712.58 247120.50 -10970.01 -18210.44 -6132.86 -52240.73 -19340.80 169917.83 -87544.39 -14745.72 369390.43 -2243.35 78356.91 -618.21 -73468.71 113662.67 -32029.68 217965.70 6922.0000 108474.0 1641726.0 295080.5 -2.717 1.716 9099845.78 10278670.8288 0.5000 388648.16 672346.44 523813.82 179272.73 143237.35 -23828.01 -26426.86 -9288.31 130818.56 10848.06 80126.47 199052.08 -54048.36 562720.47 428897.71 157519.51 -49771.42 -38585.22 198793.59 -41702.60 -55170.40 328924.55 -38532.78 638121.31 82337.46 -19266.79 374849.82 36781.83 40839.37 459302.23 13776.24 -60335.77 -52474.61 -3892.66 308830.00 170752.88 -12940.66 533910.29 -32203.15 105197.46 -4579.55 767756.14 470172.54 192161.92 54539.36 270370.56 -25394.73 -13256.13 -28438.05 264131.67 -5296.58 154772.18 -24307.41 -12717.96 -3569.43 164294.45 216975.65 389819.72 -43662.48 -61559.76 -5179.87 94455.12 68302.55 -31194.92 6927.0000 108183.0 1637764.0 295081.5 -2.717 1.714 6913071.88 10655300.4342 0.5000 252997.35 146202.54 -20143.06 166291.42 478239.89 -15245.91 241066.30 892037.59 30055.41 26569.29 -18963.93 -52547.75 -7778.36 665512.66 321108.96 -7330.62 -4992.67 -72195.55 -33564.24 36970.05 -19453.16 145710.39 7210.57 271347.83 134907.53 559452.65 -22718.89 44485.74 311239.99 648890.80 -43491.14 365036.73 103054.76 85826.55 -10587.68 171858.66 219394.94 113446.85 76539.88 212918.00 -30767.21 100902.77 -57468.26 -29552.13 114026.72 356607.93 16867.18 -21828.87 -28344.87 -39659.98 -78626.70 -7579.99 -18246.21 94921.76 36276.76 -11083.56 -12283.48 81419.01 -60623.67 116170.67 -27800.29 21024.00 -39.34 -600.72 6932.0000 106587.0 1613746.0 295083.5 -2.717 1.699 10105332.26 9346514.1243 0.5000 70999.97 671639.66 100746.97 -50466.13 180646.73 371747.26 27040.41 -38820.46 210770.91 109409.64 426746.80 -25636.44 709006.61 -43193.62 158345.44 236952.14 -26740.35 -13963.00 351078.03 214539.53 217651.74 480419.04 -1349.22 162630.78 9663.93 247932.24 -53587.21 -22906.08 -478.60 536088.63 -488.26 372896.99 15890.97 114261.48 3446.13 -15841.29 411066.81 -74108.10 -19437.23 732304.44 -8511.52 -20428.18 112549.69 64122.86 23501.66 -8777.49 426582.51 356181.24 -16.91 -20362.83 -60131.00 548368.66 -14238.60 380402.00 -3020.60 -2341.35 88064.37 924556.90 -56480.55 294788.70 -35404.98 158376.77 43115.64 157527.98 It is also legal to have no header section at all and just columns of white space separated numbers. In this case the columns will be labelled Column_1...Column_N. */ public class DatLoader extends AbstractFileLoader implements IMetaLoader { transient protected static final Logger logger = LoggerFactory.getLogger(DatLoader.class); transient private static final String FLOAT = "([-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?)|(0\\.)"; transient private static final Pattern DATA = Pattern.compile("^(("+FLOAT+")\\s+)+("+FLOAT+")$"); protected String fileName; protected List<String> header; protected Map<String,String> metaData; protected List<String> footer; protected Map<String, List<Double>> vals; protected int columnIndex; private ExtendedMetadata metadata; public DatLoader() { } /** * @param fileName */ public DatLoader(final String fileName) { setFile(fileName); } public void setFile(final String fileName) { this.fileName = fileName; this.header = new ArrayList<String>(31); this.metaData = new HashMap<String,String>(7); this.footer = new ArrayList<String>(7); // Important must use LinkedHashMap as order assumes is insertion order. this.vals = new LinkedHashMap<String, List<Double>>(); } @Override public DataHolder loadFile() throws ScanFileHolderException { return loadFile((IMonitor)null); } /** * Function that loads in the standard SRS datafile * * @return The package which contains the data that has been loaded * @throws ScanFileHolderException */ @Override public DataHolder loadFile(final IMonitor mon) throws ScanFileHolderException { final DataHolder result = loadFile(null, mon); return result; } private DataHolder loadFile(final String name, final IMonitor mon) throws ScanFileHolderException { // first instantiate the return object. final DataHolder result = new DataHolder(); // then try to read the file given BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8")); boolean readingFooter = false; String line = parseHeaders(in, name, mon); // Read data DATA: while (line != null) { if (mon!=null) mon.worked(1); if (mon!=null && mon.isCancelled()) { throw new ScanFileHolderException("Loader cancelled during reading!"); } line = line.trim(); if (!readingFooter && DATA.matcher(line).matches()) { if (line.startsWith("#")) { readingFooter = true; break DATA; } if (vals.isEmpty()) throw new ScanFileHolderException("Cannot read header for data set names!"); final String[] values = line.split("\\s+"); if (columnIndex>-1 && name!=null) { final String value = values[columnIndex]; vals.get(name).add(Utils.parseDouble(value.trim())); } else { if (values.length != vals.size()) { throw new ScanFileHolderException("Data and header must be the same size!"); } final Iterator<String> it = vals.keySet().iterator(); for (String value : values) { vals.get(it.next()).add(Utils.parseDouble(value.trim())); } } } line = in.readLine(); } // Footer footer.clear(); while ((line =in.readLine()) != null) { if (readingFooter) { if (line.startsWith("#")) { footer.add(line); continue; } throw new ScanFileHolderException("Every line in the footer must start with #"); } } for (String n : vals.keySet()) { final AbstractDataset set = AbstractDataset.createFromList(vals.get(n)); set.setName(n); result.addDataset(n, set); } if (loadMetadata) { createMetadata(); result.setMetadata(metadata); } return result; } catch (Exception e) { throw new ScanFileHolderException("DatLoader.loadFile exception loading " + fileName, e); } finally { try { if (in!=null) in.close(); } catch (IOException e) { throw new ScanFileHolderException("Cannot close stream from file " + fileName, e); } } } public AbstractDataset loadSet(final String path, final String name, final IMonitor mon) throws Exception { setFile(path); /** * TODO Instead of **loading everything each time**, we should get the column * number from the name, and write the algorithm to extract */ final DataHolder dh = loadFile(name, mon); return dh.getDataset(name); } /** * There are no efficiency gains in using this method, it reads everything in and garbage * collects what is not needed. */ public Map<String,ILazyDataset> loadSets(String path, List<String> names, IMonitor mon) throws Exception { setFile(path); /** * TODO Instead of **loading everything each time**, we should get the column * number from the name, and write the algorithm to extract */ final DataHolder dh = loadFile(mon); final Map<String,ILazyDataset> ret = dh.toLazyMap(); ret.keySet().retainAll(names); return ret; } @Override public void loadMetaData(final IMonitor mon) throws Exception { final BufferedReader br = new BufferedReader(new FileReader(new File(fileName))); int count = 1; try { parseHeaders(br, null, mon); // We assume the rest of the lines not starting with # are all // data lines in getting the meta data. We do not parse these lines. String line=null; while ((line = br.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) break; count++; } } finally { br.close(); } createMetadata(count); } private void createMetadata() { createMetadata(-1); } private void createMetadata(int approxSize) { metadata = new ExtendedMetadata(new File(fileName)); metadata.setMetadata(metaData); for (Entry<String, List<Double>> e : vals.entrySet()) { if (approxSize>-1 && e.getValue().size()<1) { metadata.addDataInfo(e.getKey(), approxSize); } else { metadata.addDataInfo(e.getKey(), e.getValue().size()); } } } @Override public IMetaData getMetaData() { return metadata; } private static Pattern SCAN_LINE = Pattern.compile("#S \\d+ .*"); private static Pattern DATE_LINE = Pattern.compile("#D (Sun|Mon|Tue|Wed|Thu|Fri|Sat) [a-zA-Z]+ \\d+ .*"); /** * This method parses the headers. It tries to throw an exception * if it is sure an SRS file is found. Also it looks in the headers * and if it finds "#S" and "#D" it thinks that the file is a multi-scan * spec file and throws an exception. * * Example of multi-scan spec file characteristic lines: #S 1 ascan pvo -0.662 1.338 20 0.1 #D Sat Apr 02 10:19:13 2011 * * @param in * @param name * @param mon * @return last line * @throws Exception */ private String parseHeaders(final BufferedReader in, final String name, IMonitor mon) throws Exception { String line = in.readLine(); if (line.trim().startsWith("&")) throw new Exception("Cannot load SRS files with DatLoader!"); metaData.clear(); header.clear(); vals.clear(); boolean foundHeaderLine = false; boolean wasScanLine = false; while (line.startsWith("#") || "".equals(line.trim())) { try { if ("".equals(line.trim())) continue; foundHeaderLine = true; if (mon!=null) mon.worked(1); if (mon!=null && mon.isCancelled()) { throw new ScanFileHolderException("Loader cancelled during reading!"); } if (wasScanLine && DATE_LINE.matcher(line.trim()).matches()) { throw new ScanFileHolderException("This file is a multi-scan spec file - use SpecLoader instead!"); } wasScanLine = SCAN_LINE.matcher(line.trim()).matches(); header.add(line); // This caused problems with some of B18's files, so changing the methodology a little // if (line.indexOf("=")>-1) { // metaData.put(line.substring(0,line.indexOf("=")-1), line.substring(line.indexOf("=")+1)); // } else if (line.indexOf(":")>-1) { // metaData.put(line.substring(0,line.indexOf(":")-1), line.substring(line.indexOf(":")+1)); // } if (line.contains(":")) { String[] parts = line.split(":"); String key = parts[0].replace("#", ""); String value = parts[1]; for (int p = 2; p < parts.length; p++) { value = value+":"+parts[p]; } metaData.put(key.trim(),value.trim()); } } finally { line = in.readLine(); } } if (header.size() < 1) { if (!foundHeaderLine) { final String[] values = line.trim().split("\\s+"); this.columnIndex = -1; - int p = (int) Math.ceil(Math.log10(values.length)); + int p = (int) Math.max(1, Math.ceil(Math.log10(values.length))); String fmt = String.format("col%%0%dd", p); // same as python loader for (int i = 0; i < values.length; i++) { vals.put(String.format(fmt, i+1), new ArrayList<Double>(89)); } } return line; } final String lastHeaderLine = header.get(header.size()-1); final String[] values = line.trim().split("\\s+"); if (name!=null) { this.columnIndex = -1; vals.put(name, new ArrayList<Double>(89)); // Busy line, been looking at too much python... List<String> headers = new ArrayList<String>(Arrays.asList(lastHeaderLine.substring(1).trim().split("\\s{2,}|\\,\\s+|\\t"))); if (values.length > headers.size()) { for (int j = headers.size(); j < values.length; j++) { headers.add("Unknown"+j); } } for (int i = 0; i < headers.size(); i++) { if (headers.get(i).equals(name)) { columnIndex = i; break; } } } else { createValues(vals, lastHeaderLine); // Check first line and headers are the same, sometimes the value names are not // provided in parsable syntax if (values.length > vals.size()) { for (int j = vals.size(); j < values.length; j++) { vals.put("Unknown"+j, new ArrayList<Double>(89)); } } } return line; } private void createValues(Map<String, List<Double>> v, String header) { // Two or more spaces or a comma and one more more space final String[] headers = header.substring(1).trim().split("\\s{2,}|\\,\\s+|\\t"); for (String name : headers) { v.put(name, new ArrayList<Double>(89)); } } }
true
true
private String parseHeaders(final BufferedReader in, final String name, IMonitor mon) throws Exception { String line = in.readLine(); if (line.trim().startsWith("&")) throw new Exception("Cannot load SRS files with DatLoader!"); metaData.clear(); header.clear(); vals.clear(); boolean foundHeaderLine = false; boolean wasScanLine = false; while (line.startsWith("#") || "".equals(line.trim())) { try { if ("".equals(line.trim())) continue; foundHeaderLine = true; if (mon!=null) mon.worked(1); if (mon!=null && mon.isCancelled()) { throw new ScanFileHolderException("Loader cancelled during reading!"); } if (wasScanLine && DATE_LINE.matcher(line.trim()).matches()) { throw new ScanFileHolderException("This file is a multi-scan spec file - use SpecLoader instead!"); } wasScanLine = SCAN_LINE.matcher(line.trim()).matches(); header.add(line); // This caused problems with some of B18's files, so changing the methodology a little // if (line.indexOf("=")>-1) { // metaData.put(line.substring(0,line.indexOf("=")-1), line.substring(line.indexOf("=")+1)); // } else if (line.indexOf(":")>-1) { // metaData.put(line.substring(0,line.indexOf(":")-1), line.substring(line.indexOf(":")+1)); // } if (line.contains(":")) { String[] parts = line.split(":"); String key = parts[0].replace("#", ""); String value = parts[1]; for (int p = 2; p < parts.length; p++) { value = value+":"+parts[p]; } metaData.put(key.trim(),value.trim()); } } finally { line = in.readLine(); } } if (header.size() < 1) { if (!foundHeaderLine) { final String[] values = line.trim().split("\\s+"); this.columnIndex = -1; int p = (int) Math.ceil(Math.log10(values.length)); String fmt = String.format("col%%0%dd", p); // same as python loader for (int i = 0; i < values.length; i++) { vals.put(String.format(fmt, i+1), new ArrayList<Double>(89)); } } return line; } final String lastHeaderLine = header.get(header.size()-1); final String[] values = line.trim().split("\\s+"); if (name!=null) { this.columnIndex = -1; vals.put(name, new ArrayList<Double>(89)); // Busy line, been looking at too much python... List<String> headers = new ArrayList<String>(Arrays.asList(lastHeaderLine.substring(1).trim().split("\\s{2,}|\\,\\s+|\\t"))); if (values.length > headers.size()) { for (int j = headers.size(); j < values.length; j++) { headers.add("Unknown"+j); } } for (int i = 0; i < headers.size(); i++) { if (headers.get(i).equals(name)) { columnIndex = i; break; } } } else { createValues(vals, lastHeaderLine); // Check first line and headers are the same, sometimes the value names are not // provided in parsable syntax if (values.length > vals.size()) { for (int j = vals.size(); j < values.length; j++) { vals.put("Unknown"+j, new ArrayList<Double>(89)); } } } return line; }
private String parseHeaders(final BufferedReader in, final String name, IMonitor mon) throws Exception { String line = in.readLine(); if (line.trim().startsWith("&")) throw new Exception("Cannot load SRS files with DatLoader!"); metaData.clear(); header.clear(); vals.clear(); boolean foundHeaderLine = false; boolean wasScanLine = false; while (line.startsWith("#") || "".equals(line.trim())) { try { if ("".equals(line.trim())) continue; foundHeaderLine = true; if (mon!=null) mon.worked(1); if (mon!=null && mon.isCancelled()) { throw new ScanFileHolderException("Loader cancelled during reading!"); } if (wasScanLine && DATE_LINE.matcher(line.trim()).matches()) { throw new ScanFileHolderException("This file is a multi-scan spec file - use SpecLoader instead!"); } wasScanLine = SCAN_LINE.matcher(line.trim()).matches(); header.add(line); // This caused problems with some of B18's files, so changing the methodology a little // if (line.indexOf("=")>-1) { // metaData.put(line.substring(0,line.indexOf("=")-1), line.substring(line.indexOf("=")+1)); // } else if (line.indexOf(":")>-1) { // metaData.put(line.substring(0,line.indexOf(":")-1), line.substring(line.indexOf(":")+1)); // } if (line.contains(":")) { String[] parts = line.split(":"); String key = parts[0].replace("#", ""); String value = parts[1]; for (int p = 2; p < parts.length; p++) { value = value+":"+parts[p]; } metaData.put(key.trim(),value.trim()); } } finally { line = in.readLine(); } } if (header.size() < 1) { if (!foundHeaderLine) { final String[] values = line.trim().split("\\s+"); this.columnIndex = -1; int p = (int) Math.max(1, Math.ceil(Math.log10(values.length))); String fmt = String.format("col%%0%dd", p); // same as python loader for (int i = 0; i < values.length; i++) { vals.put(String.format(fmt, i+1), new ArrayList<Double>(89)); } } return line; } final String lastHeaderLine = header.get(header.size()-1); final String[] values = line.trim().split("\\s+"); if (name!=null) { this.columnIndex = -1; vals.put(name, new ArrayList<Double>(89)); // Busy line, been looking at too much python... List<String> headers = new ArrayList<String>(Arrays.asList(lastHeaderLine.substring(1).trim().split("\\s{2,}|\\,\\s+|\\t"))); if (values.length > headers.size()) { for (int j = headers.size(); j < values.length; j++) { headers.add("Unknown"+j); } } for (int i = 0; i < headers.size(); i++) { if (headers.get(i).equals(name)) { columnIndex = i; break; } } } else { createValues(vals, lastHeaderLine); // Check first line and headers are the same, sometimes the value names are not // provided in parsable syntax if (values.length > vals.size()) { for (int j = vals.size(); j < values.length; j++) { vals.put("Unknown"+j, new ArrayList<Double>(89)); } } } return line; }
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/common/pagedlist/PendingGroupRenderer.java b/web/src/main/java/org/eurekastreams/web/client/ui/common/pagedlist/PendingGroupRenderer.java index 11d35bc99..0132e0054 100644 --- a/web/src/main/java/org/eurekastreams/web/client/ui/common/pagedlist/PendingGroupRenderer.java +++ b/web/src/main/java/org/eurekastreams/web/client/ui/common/pagedlist/PendingGroupRenderer.java @@ -1,173 +1,173 @@ /* * Copyright (c) 2009-2011 Lockheed Martin Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eurekastreams.web.client.ui.common.pagedlist; import org.eurekastreams.commons.formatting.DateFormatter; import org.eurekastreams.server.action.request.profile.ReviewPendingGroupRequest; import org.eurekastreams.server.domain.Page; import org.eurekastreams.server.search.modelview.DomainGroupModelView; import org.eurekastreams.web.client.events.EventBus; import org.eurekastreams.web.client.events.Observer; import org.eurekastreams.web.client.events.ShowNotificationEvent; import org.eurekastreams.web.client.events.data.UpdatedReviewPendingGroupResponseEvent; import org.eurekastreams.web.client.history.CreateUrlRequest; import org.eurekastreams.web.client.jsni.WidgetJSNIFacadeImpl; import org.eurekastreams.web.client.model.PendingGroupsModel; import org.eurekastreams.web.client.ui.Session; import org.eurekastreams.web.client.ui.common.notifier.Notification; import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineHyperlink; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; /** * Render a Pending Group. * */ public class PendingGroupRenderer implements ItemRenderer<DomainGroupModelView> { /** Bullet character. */ private static final String BULLET = "\u2219"; /** * {@inheritDoc} */ public Panel render(final DomainGroupModelView group) { final FlowPanel groupPanel = new FlowPanel(); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().group()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().directoryItem()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().listItem()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroup()); // -- buttons panel (left side) -- final Panel buttonsPanel = new FlowPanel(); buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroupButtons()); groupPanel.add(buttonsPanel); final Label confirmButton = new Label("Confirm"); confirmButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().approveButton()); buttonsPanel.add(confirmButton); final Label denyButton = new Label("Deny"); denyButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().denyButton()); buttonsPanel.add(denyButton); // -- group info (right side) -- FlowPanel groupAbout = new FlowPanel(); groupAbout.addStyleName(StaticResourceBundle.INSTANCE.coreCss().description()); groupPanel.add(groupAbout); Label groupName = new Label(group.getName()); groupName.addStyleName(StaticResourceBundle.INSTANCE.coreCss().displayName()); groupAbout.add(groupName); Label groupDescription = new Label(group.getDescription()); groupDescription.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroupDescription()); groupAbout.add(groupDescription); FlowPanel groupMetaData = new FlowPanel(); groupMetaData.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowers()); groupMetaData.add(new InlineLabel(new DateFormatter().timeAgo(group.getDateAdded(), true))); insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("By: ")); String url = Session.getInstance().generateUrl( new CreateUrlRequest(Page.PEOPLE, group.getPersonCreatedByAccountId())); groupMetaData.add(new InlineHyperlink(group.getPersonCreatedByDisplayName(), url)); // Display Business Area (BA) information insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("BA: ")); - Label label = new InlineLabel(group.getPersonCreatedByCompanyName()); - label.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); - groupMetaData.add(label); + Label baLabel = new InlineLabel(group.getPersonCreatedByCompanyName()); + baLabel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); + groupMetaData.add(baLabel); insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("Privacy Setting: ")); - label = new InlineLabel(group.isPublic() ? "Public" : "Private"); + Label label = new InlineLabel(group.isPublic() ? "Public" : "Private"); label.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); groupMetaData.add(label); groupAbout.add(groupMetaData); // -- actions -- confirmButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().waitActive()); PendingGroupsModel.getInstance().update(new ReviewPendingGroupRequest(group.getShortName(), true)); } }); denyButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (new WidgetJSNIFacadeImpl().confirm("Are you sure you want to deny creation of this group?")) { buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().waitActive()); PendingGroupsModel.getInstance() .update(new ReviewPendingGroupRequest(group.getShortName(), false)); } } }); final EventBus eventBus = Session.getInstance().getEventBus(); eventBus.addObserver(UpdatedReviewPendingGroupResponseEvent.class, new Observer<UpdatedReviewPendingGroupResponseEvent>() { public void update(final UpdatedReviewPendingGroupResponseEvent ev) { if (ev.getResponse().getGroupShortName().equals(group.getShortName())) { eventBus.removeObserver(ev, this); String msg = ev.getResponse().getApproved() ? "The " + group.getName() + " group has been approved" : "The request to create the " + group.getName() + " group has been denied"; eventBus.notifyObservers(new ShowNotificationEvent(new Notification(msg))); } } }); return groupPanel; } /** * Adds a separator (dot). * * @param panel * Panel to put the separator in. */ private void insertActionSeparator(final Panel panel) { Label sep = new InlineLabel(BULLET); sep.addStyleName(StaticResourceBundle.INSTANCE.coreCss().actionLinkSeparator()); panel.add(sep); } }
false
true
public Panel render(final DomainGroupModelView group) { final FlowPanel groupPanel = new FlowPanel(); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().group()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().directoryItem()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().listItem()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroup()); // -- buttons panel (left side) -- final Panel buttonsPanel = new FlowPanel(); buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroupButtons()); groupPanel.add(buttonsPanel); final Label confirmButton = new Label("Confirm"); confirmButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().approveButton()); buttonsPanel.add(confirmButton); final Label denyButton = new Label("Deny"); denyButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().denyButton()); buttonsPanel.add(denyButton); // -- group info (right side) -- FlowPanel groupAbout = new FlowPanel(); groupAbout.addStyleName(StaticResourceBundle.INSTANCE.coreCss().description()); groupPanel.add(groupAbout); Label groupName = new Label(group.getName()); groupName.addStyleName(StaticResourceBundle.INSTANCE.coreCss().displayName()); groupAbout.add(groupName); Label groupDescription = new Label(group.getDescription()); groupDescription.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroupDescription()); groupAbout.add(groupDescription); FlowPanel groupMetaData = new FlowPanel(); groupMetaData.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowers()); groupMetaData.add(new InlineLabel(new DateFormatter().timeAgo(group.getDateAdded(), true))); insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("By: ")); String url = Session.getInstance().generateUrl( new CreateUrlRequest(Page.PEOPLE, group.getPersonCreatedByAccountId())); groupMetaData.add(new InlineHyperlink(group.getPersonCreatedByDisplayName(), url)); // Display Business Area (BA) information insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("BA: ")); Label label = new InlineLabel(group.getPersonCreatedByCompanyName()); label.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); groupMetaData.add(label); insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("Privacy Setting: ")); label = new InlineLabel(group.isPublic() ? "Public" : "Private"); label.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); groupMetaData.add(label); groupAbout.add(groupMetaData); // -- actions -- confirmButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().waitActive()); PendingGroupsModel.getInstance().update(new ReviewPendingGroupRequest(group.getShortName(), true)); } }); denyButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (new WidgetJSNIFacadeImpl().confirm("Are you sure you want to deny creation of this group?")) { buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().waitActive()); PendingGroupsModel.getInstance() .update(new ReviewPendingGroupRequest(group.getShortName(), false)); } } }); final EventBus eventBus = Session.getInstance().getEventBus(); eventBus.addObserver(UpdatedReviewPendingGroupResponseEvent.class, new Observer<UpdatedReviewPendingGroupResponseEvent>() { public void update(final UpdatedReviewPendingGroupResponseEvent ev) { if (ev.getResponse().getGroupShortName().equals(group.getShortName())) { eventBus.removeObserver(ev, this); String msg = ev.getResponse().getApproved() ? "The " + group.getName() + " group has been approved" : "The request to create the " + group.getName() + " group has been denied"; eventBus.notifyObservers(new ShowNotificationEvent(new Notification(msg))); } } }); return groupPanel; }
public Panel render(final DomainGroupModelView group) { final FlowPanel groupPanel = new FlowPanel(); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().group()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().directoryItem()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().listItem()); groupPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroup()); // -- buttons panel (left side) -- final Panel buttonsPanel = new FlowPanel(); buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroupButtons()); groupPanel.add(buttonsPanel); final Label confirmButton = new Label("Confirm"); confirmButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().approveButton()); buttonsPanel.add(confirmButton); final Label denyButton = new Label("Deny"); denyButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().denyButton()); buttonsPanel.add(denyButton); // -- group info (right side) -- FlowPanel groupAbout = new FlowPanel(); groupAbout.addStyleName(StaticResourceBundle.INSTANCE.coreCss().description()); groupPanel.add(groupAbout); Label groupName = new Label(group.getName()); groupName.addStyleName(StaticResourceBundle.INSTANCE.coreCss().displayName()); groupAbout.add(groupName); Label groupDescription = new Label(group.getDescription()); groupDescription.addStyleName(StaticResourceBundle.INSTANCE.coreCss().pendingGroupDescription()); groupAbout.add(groupDescription); FlowPanel groupMetaData = new FlowPanel(); groupMetaData.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowers()); groupMetaData.add(new InlineLabel(new DateFormatter().timeAgo(group.getDateAdded(), true))); insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("By: ")); String url = Session.getInstance().generateUrl( new CreateUrlRequest(Page.PEOPLE, group.getPersonCreatedByAccountId())); groupMetaData.add(new InlineHyperlink(group.getPersonCreatedByDisplayName(), url)); // Display Business Area (BA) information insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("BA: ")); Label baLabel = new InlineLabel(group.getPersonCreatedByCompanyName()); baLabel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); groupMetaData.add(baLabel); insertActionSeparator(groupMetaData); groupMetaData.add(new InlineLabel("Privacy Setting: ")); Label label = new InlineLabel(group.isPublic() ? "Public" : "Private"); label.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectionItemFollowersData()); groupMetaData.add(label); groupAbout.add(groupMetaData); // -- actions -- confirmButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().waitActive()); PendingGroupsModel.getInstance().update(new ReviewPendingGroupRequest(group.getShortName(), true)); } }); denyButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (new WidgetJSNIFacadeImpl().confirm("Are you sure you want to deny creation of this group?")) { buttonsPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().waitActive()); PendingGroupsModel.getInstance() .update(new ReviewPendingGroupRequest(group.getShortName(), false)); } } }); final EventBus eventBus = Session.getInstance().getEventBus(); eventBus.addObserver(UpdatedReviewPendingGroupResponseEvent.class, new Observer<UpdatedReviewPendingGroupResponseEvent>() { public void update(final UpdatedReviewPendingGroupResponseEvent ev) { if (ev.getResponse().getGroupShortName().equals(group.getShortName())) { eventBus.removeObserver(ev, this); String msg = ev.getResponse().getApproved() ? "The " + group.getName() + " group has been approved" : "The request to create the " + group.getName() + " group has been denied"; eventBus.notifyObservers(new ShowNotificationEvent(new Notification(msg))); } } }); return groupPanel; }
diff --git a/apps/viewer/src/main/java/org/iplantc/phyloviewer/viewer/client/Phyloviewer.java b/apps/viewer/src/main/java/org/iplantc/phyloviewer/viewer/client/Phyloviewer.java index ba44ad5a..16445064 100644 --- a/apps/viewer/src/main/java/org/iplantc/phyloviewer/viewer/client/Phyloviewer.java +++ b/apps/viewer/src/main/java/org/iplantc/phyloviewer/viewer/client/Phyloviewer.java @@ -1,387 +1,387 @@ /** * Copyright (c) 2009, iPlant Collaborative, Texas Advanced Computing Center * This software is licensed under the CC-GNU GPL version 2.0 or later. * License: http://creativecommons.org/licenses/GPL/2.0/ */ package org.iplantc.phyloviewer.viewer.client; import org.iplantc.phyloviewer.shared.math.Box2D; import org.iplantc.phyloviewer.shared.model.Document; import org.iplantc.phyloviewer.shared.render.Defaults; import org.iplantc.phyloviewer.shared.render.RenderPreferences; import org.iplantc.phyloviewer.shared.render.style.BranchStyle; import org.iplantc.phyloviewer.shared.render.style.CompositeStyle; import org.iplantc.phyloviewer.shared.render.style.GlyphStyle; import org.iplantc.phyloviewer.shared.render.style.LabelStyle; import org.iplantc.phyloviewer.shared.render.style.NodeStyle; import org.iplantc.phyloviewer.viewer.client.TreeWidget.ViewType; import org.iplantc.phyloviewer.viewer.client.services.CombinedServiceAsync; import org.iplantc.phyloviewer.viewer.client.services.CombinedServiceAsyncImpl; import org.iplantc.phyloviewer.viewer.client.services.SearchServiceAsyncImpl; import org.iplantc.phyloviewer.viewer.client.services.TreeListService; import org.iplantc.phyloviewer.viewer.client.services.TreeListServiceAsync; import org.iplantc.phyloviewer.viewer.client.services.CombinedService.NodeResponse; import org.iplantc.phyloviewer.viewer.client.services.SearchServiceAsyncImpl.RemoteNodeSuggestion; import org.iplantc.phyloviewer.viewer.client.style.StyleByLabel; import org.iplantc.phyloviewer.viewer.client.ui.BranchStyleWidget; import org.iplantc.phyloviewer.viewer.client.ui.ColorBox; import org.iplantc.phyloviewer.viewer.client.ui.ContextMenu; import org.iplantc.phyloviewer.viewer.client.ui.GlyphStyleWidget; import org.iplantc.phyloviewer.viewer.client.ui.LabelStyleWidget; import org.iplantc.phyloviewer.viewer.client.ui.NodeStyleWidget; import org.iplantc.phyloviewer.viewer.client.ui.NodeTable; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Phyloviewer implements EntryPoint { TreeWidget widget; JSTreeList trees; CombinedServiceAsync combinedService = new CombinedServiceAsyncImpl(); SearchServiceAsyncImpl searchService = new SearchServiceAsyncImpl(); TreeListServiceAsync treeList = GWT.create(TreeListService.class); EventBus eventBus = new SimpleEventBus(); /** * This is the entry point method. */ public void onModuleLoad() { widget = new TreeWidget(searchService,eventBus); - CompositeStyle hightlightStyle = new CompositeStyle("highlight", Defaults.DEFAULT_STYLE); - hightlightStyle.setNodeStyle(new NodeStyle("#C2C2F5", Double.NaN)); - hightlightStyle.setLabelStyle(new LabelStyle(null)); - hightlightStyle.setGlyphStyle(new GlyphStyle(null, "#C2C2F5", Double.NaN)); - hightlightStyle.setBranchStyle(new BranchStyle("#C2C2F5", Double.NaN)); + CompositeStyle highlightStyle = new CompositeStyle("highlight", Defaults.DEFAULT_STYLE); + highlightStyle.setNodeStyle(new NodeStyle("#C2C2F5", Double.NaN)); + highlightStyle.setLabelStyle(new LabelStyle(null)); + highlightStyle.setGlyphStyle(new GlyphStyle(null, "#C2C2F5", Double.NaN)); + highlightStyle.setBranchStyle(new BranchStyle("#C2C2F5", Double.NaN)); RenderPreferences rp = new RenderPreferences(); - rp.setHighlightStyle(hightlightStyle); + rp.setHighlightStyle(highlightStyle); widget.setRenderPreferences(rp); MenuBar fileMenu = new MenuBar(true); fileMenu.addItem("Open...", new Command() { @Override public void execute() { Phyloviewer.this.displayTrees(); } }); Command openURL = new Command() { @Override public void execute() { Window.open(widget.exportImageURL(), "_blank", ""); } }; fileMenu.addItem("Get image (opens in a popup window)", openURL); MenuBar layoutMenu = new MenuBar(true); layoutMenu.addItem("Rectangular", new Command() { @Override public void execute() { widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_CLADOGRAM); } }); layoutMenu.addItem("Circular", new Command() { @Override public void execute() { widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_RADIAL); } }); MenuBar styleMenu = new MenuBar(true); final TextInputPopup styleTextPopup = new TextInputPopup(); styleTextPopup.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { StyleByLabel styleMap = new StyleByLabel(); styleMap.put(event.getValue()); widget.getView().getDocument().setStyleMap(styleMap); widget.render(); } }); styleTextPopup.setModal(true); styleMenu.addItem("Style by CSV", new Command() { @Override public void execute() { styleTextPopup.setPopupPositionAndShow(new PopupPanel.PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { int left = (Window.getClientWidth() - offsetWidth) / 3; int top = (Window.getClientHeight() - offsetHeight) / 3; styleTextPopup.setPopupPosition(left, top); } }); } }); // Make a search box final SuggestBox searchBox = new SuggestBox(searchService); searchBox.setLimit(10); //TODO make scrollable? searchBox.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { Box2D box = ((RemoteNodeSuggestion)event.getSelectedItem()).getResult().layout.boundingBox; widget.show(box); } }); //create some styling widgets for the context menu NodeStyleWidget nodeStyleWidget = new NodeStyleWidget(widget.getView().getDocument()); BranchStyleWidget branchStyleWidget = new BranchStyleWidget(widget.getView().getDocument()); GlyphStyleWidget glyphStyleWidget = new GlyphStyleWidget(widget.getView().getDocument()); LabelStyleWidget labelStyleWidget = new LabelStyleWidget(widget.getView().getDocument()); //replace their default TextBoxes with ColorBoxes, which jscolor.js will add a color picker to nodeStyleWidget.setColorWidget(createColorBox()); branchStyleWidget.setStrokeColorWidget(createColorBox()); glyphStyleWidget.setStrokeColorWidget(createColorBox()); glyphStyleWidget.setFillColorWidget(createColorBox()); labelStyleWidget.setColorWidget(createColorBox()); //add the widgets to separate panels on the context menu final ContextMenu contextMenuPanel = new ContextMenu(widget); contextMenuPanel.add(new NodeTable(), "Node details", 3); contextMenuPanel.add(nodeStyleWidget, "Node", 3); contextMenuPanel.add(branchStyleWidget, "Branch", 3); contextMenuPanel.add(glyphStyleWidget, "Glyph", 3); contextMenuPanel.add(labelStyleWidget, "Label", 3); HorizontalPanel searchPanel = new HorizontalPanel(); searchPanel.add(new Label("Search:")); searchPanel.add(searchBox); // Make the UI. MenuBar menu = new MenuBar(); final DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.EM); mainPanel.addNorth(menu, 2); mainPanel.addSouth(searchPanel, 2); mainPanel.addWest(contextMenuPanel, 0); mainPanel.add(widget); RootLayoutPanel.get().add(mainPanel); MenuBar viewMenu = new MenuBar(true); viewMenu.addItem("Layout", layoutMenu); viewMenu.addItem("Style", styleMenu); contextMenuPanel.setVisible(false); viewMenu.addItem("Toggle Context Panel", new Command() { @Override public void execute() { if(contextMenuPanel.isVisible()) { contextMenuPanel.setVisible(false); mainPanel.setWidgetSize(contextMenuPanel,0); mainPanel.forceLayout(); } else { contextMenuPanel.setVisible(true); mainPanel.setWidgetSize(contextMenuPanel, 20); mainPanel.forceLayout(); } } }); menu.addItem("File", fileMenu); menu.addItem("View", viewMenu); // Draw for the first time. RootLayoutPanel.get().forceLayout(); mainPanel.forceLayout(); widget.setViewType(ViewType.VIEW_TYPE_CLADOGRAM); widget.render(); initColorPicker(); // Present the user the dialog to load a tree. this.displayTrees(); } private ColorBox createColorBox() { ColorBox colorBox = new ColorBox(); colorBox.addStyleName("{hash:true,required:false}"); //jscolor config return colorBox; } private final native void initColorPicker() /*-{ $wnd.jscolor.init(); }-*/; private void displayTrees() { final PopupPanel displayTreePanel = new PopupPanel(); displayTreePanel.setModal(true); displayTreePanel.setPopupPositionAndShow(new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { int left = (Window.getClientWidth() - offsetWidth) / 2; int top = (Window.getClientHeight() - offsetHeight)/2 - 100; displayTreePanel.setPopupPosition(left, top); } }); final VerticalPanel vPanel = new VerticalPanel(); displayTreePanel.add(vPanel); Label messageLabel = new Label ("Select a tree to load:"); vPanel.add(messageLabel); final Label label = new Label ( "Retrieving tree list..."); vPanel.add(label); final ListBox lb = new ListBox(); lb.setVisible(false); vPanel.add(lb); final HorizontalPanel hPanel = new HorizontalPanel(); hPanel.add(new Button("OK",new ClickHandler() { @Override public void onClick(ClickEvent arg0) { label.setText("Loading..."); label.setVisible(true); lb.setVisible(false); hPanel.setVisible(false); int index = lb.getSelectedIndex(); if ( index >= 0 && trees != null ) { final JSTreeData data = trees.getTree ( index ); if ( data != null ) { combinedService.getRootNode(data.getId(), new AsyncCallback<NodeResponse>() { @Override public void onFailure(Throwable arg0) { Window.alert(arg0.getMessage()); displayTreePanel.hide(); } @Override public void onSuccess(NodeResponse response) { Document document = new PagedDocument(combinedService, eventBus, data.getId(), response); searchService.setTree(document.getTree()); widget.setDocument(document); displayTreePanel.hide(); } }); } } } })); hPanel.add(new Button("Cancel",new ClickHandler() { @Override public void onClick(ClickEvent arg0) { displayTreePanel.hide(); } })); vPanel.add(hPanel); displayTreePanel.show(); treeList.getTreeList(new AsyncCallback<String>() { @Override public void onFailure(Throwable arg0) { Window.alert(arg0.getMessage()); } @Override public void onSuccess(String json) { trees = JSTreeList.parseJSON(json); for(int i = 0; i < trees.getNumberOfTrees(); ++i ) { lb.addItem(trees.getTree(i).getName()); } label.setVisible(false); lb.setVisible(true); } }); } private class TextInputPopup extends PopupPanel implements HasValueChangeHandlers<String> { public TextInputPopup() { VerticalPanel vPanel = new VerticalPanel(); final TextArea textBox = new TextArea(); textBox.setVisibleLines(20); textBox.setCharacterWidth(80); Button okButton = new Button("OK", new ClickHandler() { @Override public void onClick(ClickEvent event) { ValueChangeEvent.fire(TextInputPopup.this, textBox.getValue()); TextInputPopup.this.hide(); } }); vPanel.add(textBox); vPanel.add(okButton); this.add(vPanel); } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { return addHandler(handler, ValueChangeEvent.getType()); } } }
false
true
public void onModuleLoad() { widget = new TreeWidget(searchService,eventBus); CompositeStyle hightlightStyle = new CompositeStyle("highlight", Defaults.DEFAULT_STYLE); hightlightStyle.setNodeStyle(new NodeStyle("#C2C2F5", Double.NaN)); hightlightStyle.setLabelStyle(new LabelStyle(null)); hightlightStyle.setGlyphStyle(new GlyphStyle(null, "#C2C2F5", Double.NaN)); hightlightStyle.setBranchStyle(new BranchStyle("#C2C2F5", Double.NaN)); RenderPreferences rp = new RenderPreferences(); rp.setHighlightStyle(hightlightStyle); widget.setRenderPreferences(rp); MenuBar fileMenu = new MenuBar(true); fileMenu.addItem("Open...", new Command() { @Override public void execute() { Phyloviewer.this.displayTrees(); } }); Command openURL = new Command() { @Override public void execute() { Window.open(widget.exportImageURL(), "_blank", ""); } }; fileMenu.addItem("Get image (opens in a popup window)", openURL); MenuBar layoutMenu = new MenuBar(true); layoutMenu.addItem("Rectangular", new Command() { @Override public void execute() { widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_CLADOGRAM); } }); layoutMenu.addItem("Circular", new Command() { @Override public void execute() { widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_RADIAL); } }); MenuBar styleMenu = new MenuBar(true); final TextInputPopup styleTextPopup = new TextInputPopup(); styleTextPopup.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { StyleByLabel styleMap = new StyleByLabel(); styleMap.put(event.getValue()); widget.getView().getDocument().setStyleMap(styleMap); widget.render(); } }); styleTextPopup.setModal(true); styleMenu.addItem("Style by CSV", new Command() { @Override public void execute() { styleTextPopup.setPopupPositionAndShow(new PopupPanel.PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { int left = (Window.getClientWidth() - offsetWidth) / 3; int top = (Window.getClientHeight() - offsetHeight) / 3; styleTextPopup.setPopupPosition(left, top); } }); } }); // Make a search box final SuggestBox searchBox = new SuggestBox(searchService); searchBox.setLimit(10); //TODO make scrollable? searchBox.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { Box2D box = ((RemoteNodeSuggestion)event.getSelectedItem()).getResult().layout.boundingBox; widget.show(box); } }); //create some styling widgets for the context menu NodeStyleWidget nodeStyleWidget = new NodeStyleWidget(widget.getView().getDocument()); BranchStyleWidget branchStyleWidget = new BranchStyleWidget(widget.getView().getDocument()); GlyphStyleWidget glyphStyleWidget = new GlyphStyleWidget(widget.getView().getDocument()); LabelStyleWidget labelStyleWidget = new LabelStyleWidget(widget.getView().getDocument()); //replace their default TextBoxes with ColorBoxes, which jscolor.js will add a color picker to nodeStyleWidget.setColorWidget(createColorBox()); branchStyleWidget.setStrokeColorWidget(createColorBox()); glyphStyleWidget.setStrokeColorWidget(createColorBox()); glyphStyleWidget.setFillColorWidget(createColorBox()); labelStyleWidget.setColorWidget(createColorBox()); //add the widgets to separate panels on the context menu final ContextMenu contextMenuPanel = new ContextMenu(widget); contextMenuPanel.add(new NodeTable(), "Node details", 3); contextMenuPanel.add(nodeStyleWidget, "Node", 3); contextMenuPanel.add(branchStyleWidget, "Branch", 3); contextMenuPanel.add(glyphStyleWidget, "Glyph", 3); contextMenuPanel.add(labelStyleWidget, "Label", 3); HorizontalPanel searchPanel = new HorizontalPanel(); searchPanel.add(new Label("Search:")); searchPanel.add(searchBox); // Make the UI. MenuBar menu = new MenuBar(); final DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.EM); mainPanel.addNorth(menu, 2); mainPanel.addSouth(searchPanel, 2); mainPanel.addWest(contextMenuPanel, 0); mainPanel.add(widget); RootLayoutPanel.get().add(mainPanel); MenuBar viewMenu = new MenuBar(true); viewMenu.addItem("Layout", layoutMenu); viewMenu.addItem("Style", styleMenu); contextMenuPanel.setVisible(false); viewMenu.addItem("Toggle Context Panel", new Command() { @Override public void execute() { if(contextMenuPanel.isVisible()) { contextMenuPanel.setVisible(false); mainPanel.setWidgetSize(contextMenuPanel,0); mainPanel.forceLayout(); } else { contextMenuPanel.setVisible(true); mainPanel.setWidgetSize(contextMenuPanel, 20); mainPanel.forceLayout(); } } }); menu.addItem("File", fileMenu); menu.addItem("View", viewMenu); // Draw for the first time. RootLayoutPanel.get().forceLayout(); mainPanel.forceLayout(); widget.setViewType(ViewType.VIEW_TYPE_CLADOGRAM); widget.render(); initColorPicker(); // Present the user the dialog to load a tree. this.displayTrees(); }
public void onModuleLoad() { widget = new TreeWidget(searchService,eventBus); CompositeStyle highlightStyle = new CompositeStyle("highlight", Defaults.DEFAULT_STYLE); highlightStyle.setNodeStyle(new NodeStyle("#C2C2F5", Double.NaN)); highlightStyle.setLabelStyle(new LabelStyle(null)); highlightStyle.setGlyphStyle(new GlyphStyle(null, "#C2C2F5", Double.NaN)); highlightStyle.setBranchStyle(new BranchStyle("#C2C2F5", Double.NaN)); RenderPreferences rp = new RenderPreferences(); rp.setHighlightStyle(highlightStyle); widget.setRenderPreferences(rp); MenuBar fileMenu = new MenuBar(true); fileMenu.addItem("Open...", new Command() { @Override public void execute() { Phyloviewer.this.displayTrees(); } }); Command openURL = new Command() { @Override public void execute() { Window.open(widget.exportImageURL(), "_blank", ""); } }; fileMenu.addItem("Get image (opens in a popup window)", openURL); MenuBar layoutMenu = new MenuBar(true); layoutMenu.addItem("Rectangular", new Command() { @Override public void execute() { widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_CLADOGRAM); } }); layoutMenu.addItem("Circular", new Command() { @Override public void execute() { widget.setViewType(TreeWidget.ViewType.VIEW_TYPE_RADIAL); } }); MenuBar styleMenu = new MenuBar(true); final TextInputPopup styleTextPopup = new TextInputPopup(); styleTextPopup.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { StyleByLabel styleMap = new StyleByLabel(); styleMap.put(event.getValue()); widget.getView().getDocument().setStyleMap(styleMap); widget.render(); } }); styleTextPopup.setModal(true); styleMenu.addItem("Style by CSV", new Command() { @Override public void execute() { styleTextPopup.setPopupPositionAndShow(new PopupPanel.PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { int left = (Window.getClientWidth() - offsetWidth) / 3; int top = (Window.getClientHeight() - offsetHeight) / 3; styleTextPopup.setPopupPosition(left, top); } }); } }); // Make a search box final SuggestBox searchBox = new SuggestBox(searchService); searchBox.setLimit(10); //TODO make scrollable? searchBox.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { Box2D box = ((RemoteNodeSuggestion)event.getSelectedItem()).getResult().layout.boundingBox; widget.show(box); } }); //create some styling widgets for the context menu NodeStyleWidget nodeStyleWidget = new NodeStyleWidget(widget.getView().getDocument()); BranchStyleWidget branchStyleWidget = new BranchStyleWidget(widget.getView().getDocument()); GlyphStyleWidget glyphStyleWidget = new GlyphStyleWidget(widget.getView().getDocument()); LabelStyleWidget labelStyleWidget = new LabelStyleWidget(widget.getView().getDocument()); //replace their default TextBoxes with ColorBoxes, which jscolor.js will add a color picker to nodeStyleWidget.setColorWidget(createColorBox()); branchStyleWidget.setStrokeColorWidget(createColorBox()); glyphStyleWidget.setStrokeColorWidget(createColorBox()); glyphStyleWidget.setFillColorWidget(createColorBox()); labelStyleWidget.setColorWidget(createColorBox()); //add the widgets to separate panels on the context menu final ContextMenu contextMenuPanel = new ContextMenu(widget); contextMenuPanel.add(new NodeTable(), "Node details", 3); contextMenuPanel.add(nodeStyleWidget, "Node", 3); contextMenuPanel.add(branchStyleWidget, "Branch", 3); contextMenuPanel.add(glyphStyleWidget, "Glyph", 3); contextMenuPanel.add(labelStyleWidget, "Label", 3); HorizontalPanel searchPanel = new HorizontalPanel(); searchPanel.add(new Label("Search:")); searchPanel.add(searchBox); // Make the UI. MenuBar menu = new MenuBar(); final DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.EM); mainPanel.addNorth(menu, 2); mainPanel.addSouth(searchPanel, 2); mainPanel.addWest(contextMenuPanel, 0); mainPanel.add(widget); RootLayoutPanel.get().add(mainPanel); MenuBar viewMenu = new MenuBar(true); viewMenu.addItem("Layout", layoutMenu); viewMenu.addItem("Style", styleMenu); contextMenuPanel.setVisible(false); viewMenu.addItem("Toggle Context Panel", new Command() { @Override public void execute() { if(contextMenuPanel.isVisible()) { contextMenuPanel.setVisible(false); mainPanel.setWidgetSize(contextMenuPanel,0); mainPanel.forceLayout(); } else { contextMenuPanel.setVisible(true); mainPanel.setWidgetSize(contextMenuPanel, 20); mainPanel.forceLayout(); } } }); menu.addItem("File", fileMenu); menu.addItem("View", viewMenu); // Draw for the first time. RootLayoutPanel.get().forceLayout(); mainPanel.forceLayout(); widget.setViewType(ViewType.VIEW_TYPE_CLADOGRAM); widget.render(); initColorPicker(); // Present the user the dialog to load a tree. this.displayTrees(); }
diff --git a/src/main/java/edu/mssm/pharm/maayanlab/Enrichr/Enrichr.java b/src/main/java/edu/mssm/pharm/maayanlab/Enrichr/Enrichr.java index d1cd8c0..d1779b4 100644 --- a/src/main/java/edu/mssm/pharm/maayanlab/Enrichr/Enrichr.java +++ b/src/main/java/edu/mssm/pharm/maayanlab/Enrichr/Enrichr.java @@ -1,219 +1,220 @@ /** * Enrichr is a web app that serves the enrichment pages. * * @author Edward Y. Chen * @since 8/2/2012 */ package edu.mssm.pharm.maayanlab.Enrichr; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import edu.mssm.pharm.maayanlab.FileUtils; import edu.mssm.pharm.maayanlab.JSONify; import edu.mssm.pharm.maayanlab.PartReader; @WebServlet(urlPatterns= {"/enrich", "/share", "/export"}) @MultipartConfig public class Enrichr extends HttpServlet { /** * */ private static final long serialVersionUID = 3310803710142519430L; protected static final String RESOURCE_PATH = "/datasets/"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); // Read file Part fileChunk = request.getPart("file"); if (fileChunk == null || fileChunk.getSize() == 0) fileChunk = request.getPart("list"); ArrayList<String> inputList = PartReader.readLines(fileChunk); // Read description String description = request.getParameter("description"); if (description != null && description.trim().length() != 0) request.getSession().setAttribute("description", description); else request.getSession().removeAttribute("description"); // Increment count ((AtomicInteger) getServletContext().getAttribute("EnrichrCount")).incrementAndGet(); postResult(request, response, inputList); } private void postResult(HttpServletRequest request, HttpServletResponse response, ArrayList<String> inputList) throws ServletException, IOException { try { HttpSession session = request.getSession(); // Write gene count session.setAttribute("length", Integer.toString(inputList.size())); boolean validate = ("true".equals(request.getParameter("validate"))) ? true : false; Enrichment app = new Enrichment(inputList, validate); session.setAttribute("process", app); request.getRequestDispatcher("results.jsp").forward(request, response); } catch (ParseException e) { if (e.getErrorOffset() == -1) response.getWriter().println("Invalid input: Input list is empty."); else response.getWriter().println("Invalid input: " + e.getMessage() + " at line " + (e.getErrorOffset() + 1) + " is not a valid Entrez Gene Symbol."); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Redirect to post if reading from file String dataset = request.getParameter("dataset"); if (dataset != null) { String resourceUrl = RESOURCE_PATH + dataset + ".txt"; if ((new File(resourceUrl)).isFile()) { ArrayList<String> input = FileUtils.readResource(resourceUrl); if (input.get(0).startsWith("#")) // If input line starts with comment session.setAttribute("description", input.remove(0).replaceFirst("#", "")); else session.removeAttribute("description"); postResult(request, response, input); } else { - //TODO: Add error message + request.setAttribute("error", "This dataset doesn't exist."); + request.getRequestDispatcher("error.jsp").forward(request, response); } return; } Enrichment app = (Enrichment) session.getAttribute("process"); if (app == null) { // If session is expired getExpired(request, response); return; } if (request.getServletPath().equals("/enrich")) { // Support legacy paths // TODO: remove legacy if (request.getParameter("share") == null) { // If not sharing result if (request.getParameter("filename") == null) // If not exporting file getJSONResult(request, response, app); else getFileResult(request, response, app); } else { getShared(request, response, app); } // End of legacy } else { if (request.getServletPath().equals("/share")) { getShared(request, response, app); return; } if (request.getServletPath().equals("/export")) { getFileResult(request, response, app); return; } } } private void getExpired(HttpServletRequest request, HttpServletResponse response) throws IOException { JSONify json = new JSONify(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); json.add("expired", true); json.write(response.getWriter()); } private void getShared(HttpServletRequest request, HttpServletResponse response, Enrichment app) throws IOException { JSONify json = new JSONify(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); int listNumber = ((AtomicInteger) getServletContext().getAttribute("ShareCount")).getAndIncrement(); String fileId = Shortener.encode(listNumber); String description = (String) session.getAttribute("description"); if (description != null) FileUtils.writeFile("/datasets/" + fileId + ".txt", "#" + description, app.getInput()); else FileUtils.writeFile("/datasets/" + fileId + ".txt", app.getInput()); User user = (User) session.getAttribute("user"); if (user != null) { user.getLists().add(new List(listNumber, user, description)); Account.updateUser(user); } json.add("link_id", fileId); json.write(response.getWriter()); } private void getJSONResult(HttpServletRequest request, HttpServletResponse response, Enrichment app) throws IOException { String backgroundType = request.getParameter("backgroundType"); LinkedList<Term> results = app.enrich(backgroundType); JSONify json = new JSONify(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); json.add(backgroundType, flattenResults(results)); json.write(response.getWriter()); } private void getFileResult(HttpServletRequest request, HttpServletResponse response, Enrichment app) throws IOException { String filename = request.getParameter("filename"); String backgroundType = request.getParameter("backgroundType"); LinkedList<Term> results = app.enrich(backgroundType); response.setHeader("Pragma", "public"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".txt\""); response.setHeader("Content-Transfer-Encoding", "binary"); FileUtils.write(response.getWriter(), Enrichment.HEADER, results); } private Object[][] flattenResults(LinkedList<Term> results) { Object[][] resultsMatrix = new Object[results.size()][6]; int i = 0; for (Term term : results) { resultsMatrix[i][0] = i+1; resultsMatrix[i][1] = term.getName(); resultsMatrix[i][2] = term.getAdjustedPValue(); resultsMatrix[i][3] = term.getZScore(); resultsMatrix[i][4] = term.getCombinedScore(); resultsMatrix[i][5] = term.getTargets(); i++; } return resultsMatrix; } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Redirect to post if reading from file String dataset = request.getParameter("dataset"); if (dataset != null) { String resourceUrl = RESOURCE_PATH + dataset + ".txt"; if ((new File(resourceUrl)).isFile()) { ArrayList<String> input = FileUtils.readResource(resourceUrl); if (input.get(0).startsWith("#")) // If input line starts with comment session.setAttribute("description", input.remove(0).replaceFirst("#", "")); else session.removeAttribute("description"); postResult(request, response, input); } else { //TODO: Add error message } return; } Enrichment app = (Enrichment) session.getAttribute("process"); if (app == null) { // If session is expired getExpired(request, response); return; } if (request.getServletPath().equals("/enrich")) { // Support legacy paths // TODO: remove legacy if (request.getParameter("share") == null) { // If not sharing result if (request.getParameter("filename") == null) // If not exporting file getJSONResult(request, response, app); else getFileResult(request, response, app); } else { getShared(request, response, app); } // End of legacy } else { if (request.getServletPath().equals("/share")) { getShared(request, response, app); return; } if (request.getServletPath().equals("/export")) { getFileResult(request, response, app); return; } } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Redirect to post if reading from file String dataset = request.getParameter("dataset"); if (dataset != null) { String resourceUrl = RESOURCE_PATH + dataset + ".txt"; if ((new File(resourceUrl)).isFile()) { ArrayList<String> input = FileUtils.readResource(resourceUrl); if (input.get(0).startsWith("#")) // If input line starts with comment session.setAttribute("description", input.remove(0).replaceFirst("#", "")); else session.removeAttribute("description"); postResult(request, response, input); } else { request.setAttribute("error", "This dataset doesn't exist."); request.getRequestDispatcher("error.jsp").forward(request, response); } return; } Enrichment app = (Enrichment) session.getAttribute("process"); if (app == null) { // If session is expired getExpired(request, response); return; } if (request.getServletPath().equals("/enrich")) { // Support legacy paths // TODO: remove legacy if (request.getParameter("share") == null) { // If not sharing result if (request.getParameter("filename") == null) // If not exporting file getJSONResult(request, response, app); else getFileResult(request, response, app); } else { getShared(request, response, app); } // End of legacy } else { if (request.getServletPath().equals("/share")) { getShared(request, response, app); return; } if (request.getServletPath().equals("/export")) { getFileResult(request, response, app); return; } } }
diff --git a/src/org/pentaho/pms/schema/security/SecurityService.java b/src/org/pentaho/pms/schema/security/SecurityService.java index f5f6634e..c5e55f6f 100644 --- a/src/org/pentaho/pms/schema/security/SecurityService.java +++ b/src/org/pentaho/pms/schema/security/SecurityService.java @@ -1,518 +1,518 @@ /* * Copyright 2006 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the Mozilla Public License, Version 1.1, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho * BI Platform. The Initial Developer is Pentaho Corporation. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package org.pentaho.pms.schema.security; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.pentaho.di.core.changed.ChangedFlag; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.pms.core.exception.PentahoMetadataException; import org.pentaho.pms.messages.Messages; import org.pentaho.pms.util.Const; import org.w3c.dom.Document; import org.w3c.dom.Node; public class SecurityService extends ChangedFlag implements Cloneable { public static final int SERVICE_TYPE_ALL = 0; public static final int SERVICE_TYPE_USERS = 1; public static final int SERVICE_TYPE_ROLES = 2; public static final String[] serviceTypeCodes = new String[] { "all", "users", "roles" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ public static final String[] serviceTypeDescriptions = new String[] { Messages.getString("SecurityService.USER_ALL"), //$NON-NLS-1$ Messages.getString("SecurityService.USER_USERS"), //$NON-NLS-1$ Messages.getString("SecurityService.USER_ROLES") }; //$NON-NLS-1$ public static final String ACTION = "action"; //$NON-NLS-1$ public static final String USERNAME = "userid"; //$NON-NLS-1$ public static final String PASSWORD = "password"; //$NON-NLS-1$ private String serviceURL; private String serviceName; private String detailNameParameter; private int detailServiceType; private String username; private String password; private String proxyHostname; private String proxyPort; private String nonProxyHosts; private String filename; LogWriter log = null; public SecurityService() { try { LogWriter log = LogWriter.getInstance(Const.META_EDITOR_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC); } catch (KettleException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Object clone() { try { return super.clone(); } catch (Exception e) { return null; } } public String toString() { if (hasService()) return serviceName; return "SecurityService"; //$NON-NLS-1$ } /** * @return the detailNameParameter */ public String getDetailNameParameter() { return detailNameParameter; } /** * @param detailNameParameter the detailNameParameter to set */ public void setDetailNameParameter(String detailServiceName) { this.detailNameParameter = detailServiceName; } /** * @return the detailServiceType */ public int getDetailServiceType() { return detailServiceType; } /** * @param detailServiceType the detailServiceType to set */ public void setDetailServiceType(int detailServiceType) { this.detailServiceType = detailServiceType; } /** * @return the serviceName */ public String getServiceName() { return serviceName; } /** * @param serviceName the serviceName to set */ public void setServiceName(String name) { this.serviceName = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the serviceURL */ public String getServiceURL() { return serviceURL; } /** * @param serviceURL the serviceURL to set */ public void setServiceURL(String serviceURL) { this.serviceURL = serviceURL; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } public String getServiceTypeCode() { return serviceTypeCodes[detailServiceType]; } public String getServiceTypeDesc() { return serviceTypeDescriptions[detailServiceType]; } /** * @return the nonProxyHosts */ public String getNonProxyHosts() { return nonProxyHosts; } /** * @param nonProxyHosts the nonProxyHosts to set */ public void setNonProxyHosts(String nonProxyHosts) { this.nonProxyHosts = nonProxyHosts; } /** * @return the proxyHostname */ public String getProxyHostname() { return proxyHostname; } /** * @param proxyHostname the proxyHostname to set */ public void setProxyHostname(String proxyHostname) { this.proxyHostname = proxyHostname; } /** * @return the proxyPort */ public String getProxyPort() { return proxyPort; } /** * @param proxyPort the proxyPort to set */ public void setProxyPort(String proxyPort) { this.proxyPort = proxyPort; } public static final int getServiceType(String description) { for (int i = 0; i < serviceTypeDescriptions.length; i++) { if (serviceTypeDescriptions[i].equalsIgnoreCase(description)) return i; } for (int i = 0; i < serviceTypeCodes.length; i++) { if (serviceTypeCodes[i].equalsIgnoreCase(description)) return i; } return SERVICE_TYPE_ALL; } public Node getContent() throws Exception { if (hasService()) { return getContentFromServer(); } else if (hasFile()) { return getContentFromFile(); } throw new Exception(Messages.getString("SecurityService.ERROR_0001_UNABLE_TO_GET_SECURITY_REFERENCE")); //$NON-NLS-1$ } /** * Contact the server and get back the content as XML * @return the requested security reference information * @throws Exception in case something goes awry */ public Node getContentFromServer() throws PentahoMetadataException { LogWriter log = LogWriter.getInstance(); String urlToUse = getURL(); String result = null; int status = -1; URL tempURL; try { // verify the URL is syntactically correct; we will use these pieces later in this method tempURL = new URL(urlToUse); } catch (MalformedURLException e) { String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } HttpClient client = new HttpClient(); - log.logBasic(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$ + log.logDebug(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$ // Assume we are using a proxy if proxyHostName is set? // TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1) if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) { int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ? client.getHostConfiguration().getPort(): Integer.parseInt(proxyPort); //TODO: Where to set nonProxyHosts? client.getHostConfiguration().setProxy(proxyHostname, port); //TODO: Credentials for proxy will be added if demand shows for it (post v1) // if (username != null && username.length() > 0) { // client.getState().setProxyCredentials(AuthScope.ANY, // new UsernamePasswordCredentials(username, password != null ? password : new String())); // } } // If server userid/password was supplied, use basic authentication to // authenticate with the server. if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds); client.getParams().setAuthenticationPreemptive(true); } // Get a stream for the specified URL GetMethod getMethod = new GetMethod(urlToUse); try { status = client.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { log.logDetailed(toString(), Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$ result = getMethod.getResponseBodyAsString(); log.logBasic(toString(), Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", Integer.toString(result.length()))); //$NON-NLS-1$ } else if (status == HttpStatus.SC_UNAUTHORIZED) { String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$ log.logError(toString(), msg); throw new PentahoMetadataException(msg); } } catch (HttpException e) { String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } catch (IOException e) { String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", e.getMessage()); //$NON-NLS-1$ // log.logError(toString(), msg); // log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } if (result != null){ // Get the result back... Document doc; try { doc = XMLHandler.loadXMLString(result); } catch (KettleXMLException e) { String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$ if (envelope != null) { Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$ if (body != null) { Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$ if (response != null) { Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$ return content; } } } } return null; } /** * Read the specified security file and get back the content as XML * @return the requested security reference information * @throws Exception in case something goes awry */ public Node getContentFromFile() throws Exception { try { Document doc = XMLHandler.loadXMLFile(filename); return XMLHandler.getSubNode(doc, "content"); //$NON-NLS-1$ } catch (KettleXMLException e) { throw new Exception(Messages.getString("SecurityService.ERROR_0007_UNABLE_TO_GET_SECURITY_CONTENT", filename), e); //$NON-NLS-1$ } } public String getContentAsXMLString() throws Exception { Node content = getContent(); if (content == null) return null; return content.getChildNodes().toString(); } public String getURL() { StringBuffer url = new StringBuffer(); url.append(serviceURL); url.append("?").append(ACTION).append("=").append(serviceName); //$NON-NLS-1$ //$NON-NLS-2$ url.append("&").append(detailNameParameter).append("=").append(getServiceTypeCode()); //$NON-NLS-1$ //$NON-NLS-2$ return url.toString(); } public boolean hasService() { return !Const.isEmpty(serviceURL) && !Const.isEmpty(serviceName) && !Const.isEmpty(detailNameParameter); } public boolean hasFile() { return !Const.isEmpty(filename); } /** * @return the filename */ public String getFilename() { return filename; } /** * @param filename the filename to set */ public void setFilename(String filename) { this.filename = filename; } public List<String> getUsers() { List<String> users = new ArrayList<String>(); if (hasService() || hasFile()) { try { Node contentNode = getContent(); // Load the users Node usersNode = XMLHandler.getSubNode(contentNode, "users"); //$NON-NLS-1$ int nrUsers = XMLHandler.countNodes(usersNode, "user"); //$NON-NLS-1$ for (int i = 0; i < nrUsers; i++) { Node userNode = XMLHandler.getSubNodeByNr(usersNode, "user", i); //$NON-NLS-1$ String username = XMLHandler.getNodeValue(userNode); if (username != null) users.add(username); } } catch (PentahoMetadataException ex) { log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), ex.getLocalizedMessage()); //$NON-NLS-1$ } catch (Exception e) { log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), e.getLocalizedMessage()); //$NON-NLS-1$ } } return users; } public List<String> getRoles() { List<String> roles = new ArrayList<String>(); if (hasService() || hasFile()) { try { Node contentNode = getContent(); // Load the roles Node rolesNode = XMLHandler.getSubNode(contentNode, "roles"); //$NON-NLS-1$ int nrRoles = XMLHandler.countNodes(rolesNode, "role"); //$NON-NLS-1$ for (int i=0;i<nrRoles;i++) { Node roleNode = XMLHandler.getSubNodeByNr(rolesNode, "role", i); //$NON-NLS-1$ String rolename = XMLHandler.getNodeValue(roleNode); if (rolename!=null) roles.add(rolename); } } catch (PentahoMetadataException ex) { log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), ex.getLocalizedMessage()); //$NON-NLS-1$ } catch (Exception e) { log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), e.getLocalizedMessage()); //$NON-NLS-1$ } } return roles; } public List<SecurityACL> getAcls() { List<SecurityACL> acls = new ArrayList<SecurityACL>(); if (hasService() || hasFile()) { try { Node contentNode = getContent(); // Load the ACLs Node aclsNode = XMLHandler.getSubNode(contentNode, "acls"); //$NON-NLS-1$ int nrAcls = XMLHandler.countNodes(aclsNode, "acl"); //$NON-NLS-1$ for (int i=0;i<nrAcls;i++) { Node aclNode = XMLHandler.getSubNodeByNr(aclsNode, "acl", i); //$NON-NLS-1$ SecurityACL acl = new SecurityACL(aclNode); acls.add(acl); } Collections.sort(acls); // sort by acl mask, from low to high } catch (PentahoMetadataException ex) { log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), ex.getLocalizedMessage()); //$NON-NLS-1$ } catch (Exception e) { log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), e.getLocalizedMessage()); //$NON-NLS-1$ } } return acls; } }
true
true
public Node getContentFromServer() throws PentahoMetadataException { LogWriter log = LogWriter.getInstance(); String urlToUse = getURL(); String result = null; int status = -1; URL tempURL; try { // verify the URL is syntactically correct; we will use these pieces later in this method tempURL = new URL(urlToUse); } catch (MalformedURLException e) { String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } HttpClient client = new HttpClient(); log.logBasic(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$ // Assume we are using a proxy if proxyHostName is set? // TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1) if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) { int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ? client.getHostConfiguration().getPort(): Integer.parseInt(proxyPort); //TODO: Where to set nonProxyHosts? client.getHostConfiguration().setProxy(proxyHostname, port); //TODO: Credentials for proxy will be added if demand shows for it (post v1) // if (username != null && username.length() > 0) { // client.getState().setProxyCredentials(AuthScope.ANY, // new UsernamePasswordCredentials(username, password != null ? password : new String())); // } } // If server userid/password was supplied, use basic authentication to // authenticate with the server. if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds); client.getParams().setAuthenticationPreemptive(true); } // Get a stream for the specified URL GetMethod getMethod = new GetMethod(urlToUse); try { status = client.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { log.logDetailed(toString(), Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$ result = getMethod.getResponseBodyAsString(); log.logBasic(toString(), Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", Integer.toString(result.length()))); //$NON-NLS-1$ } else if (status == HttpStatus.SC_UNAUTHORIZED) { String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$ log.logError(toString(), msg); throw new PentahoMetadataException(msg); } } catch (HttpException e) { String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } catch (IOException e) { String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", e.getMessage()); //$NON-NLS-1$ // log.logError(toString(), msg); // log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } if (result != null){ // Get the result back... Document doc; try { doc = XMLHandler.loadXMLString(result); } catch (KettleXMLException e) { String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$ if (envelope != null) { Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$ if (body != null) { Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$ if (response != null) { Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$ return content; } } } } return null; }
public Node getContentFromServer() throws PentahoMetadataException { LogWriter log = LogWriter.getInstance(); String urlToUse = getURL(); String result = null; int status = -1; URL tempURL; try { // verify the URL is syntactically correct; we will use these pieces later in this method tempURL = new URL(urlToUse); } catch (MalformedURLException e) { String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } HttpClient client = new HttpClient(); log.logDebug(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$ // Assume we are using a proxy if proxyHostName is set? // TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1) if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) { int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ? client.getHostConfiguration().getPort(): Integer.parseInt(proxyPort); //TODO: Where to set nonProxyHosts? client.getHostConfiguration().setProxy(proxyHostname, port); //TODO: Credentials for proxy will be added if demand shows for it (post v1) // if (username != null && username.length() > 0) { // client.getState().setProxyCredentials(AuthScope.ANY, // new UsernamePasswordCredentials(username, password != null ? password : new String())); // } } // If server userid/password was supplied, use basic authentication to // authenticate with the server. if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds); client.getParams().setAuthenticationPreemptive(true); } // Get a stream for the specified URL GetMethod getMethod = new GetMethod(urlToUse); try { status = client.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { log.logDetailed(toString(), Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$ result = getMethod.getResponseBodyAsString(); log.logBasic(toString(), Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", Integer.toString(result.length()))); //$NON-NLS-1$ } else if (status == HttpStatus.SC_UNAUTHORIZED) { String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$ log.logError(toString(), msg); throw new PentahoMetadataException(msg); } } catch (HttpException e) { String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } catch (IOException e) { String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", e.getMessage()); //$NON-NLS-1$ // log.logError(toString(), msg); // log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } if (result != null){ // Get the result back... Document doc; try { doc = XMLHandler.loadXMLString(result); } catch (KettleXMLException e) { String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$ log.logError(toString(), msg); log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$ if (envelope != null) { Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$ if (body != null) { Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$ if (response != null) { Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$ return content; } } } } return null; }
diff --git a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/InstallWizard2.java b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/InstallWizard2.java index 438e1a4c8..238b2e720 100644 --- a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/InstallWizard2.java +++ b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/InstallWizard2.java @@ -1,542 +1,542 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.widgets.Display; import org.eclipse.update.configuration.IInstallConfiguration; import org.eclipse.update.core.IFeature; import org.eclipse.update.core.IFeatureReference; import org.eclipse.update.core.IIncludedFeatureReference; import org.eclipse.update.core.ISite; import org.eclipse.update.core.ISiteFeatureReference; import org.eclipse.update.core.IVerificationListener; import org.eclipse.update.core.SiteManager; import org.eclipse.update.core.model.InstallAbortedException; import org.eclipse.update.internal.core.FeatureDownloadException; import org.eclipse.update.internal.core.LiteFeature; import org.eclipse.update.internal.core.UpdateCore; import org.eclipse.update.internal.operations.DuplicateConflictsValidator; import org.eclipse.update.internal.operations.InstallOperation; import org.eclipse.update.internal.operations.UpdateUtils; import org.eclipse.update.internal.ui.UpdateUI; import org.eclipse.update.internal.ui.UpdateUIImages; import org.eclipse.update.internal.ui.UpdateUIMessages; import org.eclipse.update.internal.ui.security.JarVerificationService; import org.eclipse.update.operations.IBatchOperation; import org.eclipse.update.operations.IFeatureOperation; import org.eclipse.update.operations.IInstallFeatureOperation; import org.eclipse.update.operations.IOperation; import org.eclipse.update.operations.IOperationListener; import org.eclipse.update.operations.OperationsManager; import org.eclipse.update.search.UpdateSearchRequest; public class InstallWizard2 extends Wizard implements IOperationListener, ISearchProvider { private ReviewPage reviewPage; private LicensePage licensePage; private OptionalFeaturesPage optionalFeaturesPage; private TargetPage targetPage; private IInstallConfiguration config; private int installCount = 0; private UpdateSearchRequest searchRequest; private ArrayList jobs; private boolean needsRestart; private static boolean isRunning; private IBatchOperation installOperation; private Job job; public static final Object jobFamily = new Object(); private IJobChangeListener jobListener; private boolean isUpdate; public InstallWizard2(UpdateSearchRequest searchRequest, IInstallFeatureOperation[] jobs, boolean isUpdate) { this (searchRequest, new ArrayList(Arrays.asList(jobs)), isUpdate); } public InstallWizard2(UpdateSearchRequest searchRequest, ArrayList jobs, boolean isUpdate) { this.isUpdate = isUpdate; this.searchRequest = searchRequest; this.jobs = jobs; isRunning = true; setDialogSettings(UpdateUI.getDefault().getDialogSettings()); setDefaultPageImageDescriptor(UpdateUIImages.DESC_UPDATE_WIZ); setForcePreviousAndNextButtons(true); setNeedsProgressMonitor(true); setWindowTitle(UpdateUIMessages.InstallWizard_wtitle); } public int getInstallCount() { return installCount; } public boolean isRestartNeeded() { return installCount > 0 && needsRestart; // or == selectedJobs.length } public boolean performCancel() { isRunning = false; if (targetPage != null) targetPage.removeAddedSites(); return super.performCancel(); } /** * @see Wizard#performFinish() */ public boolean performFinish() { IInstallFeatureOperation[] selectedJobs = reviewPage.getSelectedJobs(); // Check for duplication conflicts ArrayList conflicts = DuplicateConflictsValidator.computeDuplicateConflicts(selectedJobs, config); if (conflicts != null) { DuplicateConflictsDialog dialog = new DuplicateConflictsDialog(getShell(), conflicts); if (dialog.open() != 0) return false; } if (Platform.getJobManager().find(jobFamily).length > 0) { // another update/install job is running, need to wait to finish or cancel old job boolean proceed = MessageDialog.openQuestion( UpdateUI.getActiveWorkbenchShell(), UpdateUIMessages.InstallWizard_anotherJobTitle, UpdateUIMessages.InstallWizard_anotherJob); if (!proceed) return false; // cancel this job, and let the old one go on } // set the install operation installOperation = getBatchInstallOperation(selectedJobs); if (installOperation != null) launchInBackground(); return true; } public void addPages() { reviewPage = new ReviewPage(isUpdate, searchRequest, jobs); addPage(reviewPage); try { // config = UpdateUtils.createInstallConfiguration(); config = SiteManager.getLocalSite().getCurrentConfiguration(); } catch (CoreException e) { UpdateUI.logException(e); } licensePage = new LicensePage(true); addPage(licensePage); optionalFeaturesPage = new OptionalFeaturesPage(config); addPage(optionalFeaturesPage); targetPage = new TargetPage(config); addPage(targetPage); } private boolean isPageRequired(IWizardPage page) { if (page == null) return false; if (page.equals(licensePage)) { return OperationsManager.hasSelectedJobsWithLicenses( reviewPage.getSelectedJobs()); } if (page.equals(optionalFeaturesPage)) { return OperationsManager.hasSelectedJobsWithOptionalFeatures( reviewPage.getSelectedJobs()); } if (page.equals(targetPage)) { return reviewPage.getSelectedJobs().length > 0; } return true; } public IWizardPage getNextPage(IWizardPage page) { IWizardPage[] pages = getPages(); boolean start = false; IWizardPage nextPage = null; if (page.equals(reviewPage)) { updateDynamicPages(); } for (int i = 0; i < pages.length; i++) { if (pages[i].equals(page)) { start = true; } else if (start) { if (isPageRequired(pages[i])) { nextPage = pages[i]; break; } } } return nextPage; } private void updateDynamicPages() { if (licensePage != null) { IInstallFeatureOperation[] licenseJobs = OperationsManager.getSelectedJobsWithLicenses( reviewPage.getSelectedJobs()); licensePage.setJobs(licenseJobs); } if (optionalFeaturesPage != null) { IInstallFeatureOperation[] optionalJobs = OperationsManager.getSelectedJobsWithOptionalFeatures( reviewPage.getSelectedJobs()); optionalFeaturesPage.setJobs(optionalJobs); } if (targetPage != null) { IInstallFeatureOperation[] installJobs = reviewPage.getSelectedJobs(); targetPage.setJobs(installJobs); } } public boolean canFinish() { IWizardPage page = getContainer().getCurrentPage(); return page.equals(targetPage) && page.isPageComplete(); } private void preserveOriginatingURLs( IFeature feature, IFeatureReference[] optionalFeatures) { // walk the hierarchy and preserve the originating URL // for all the optional features that are not chosen to // be installed. URL url = feature.getSite().getURL(); try { IIncludedFeatureReference[] irefs = feature.getIncludedFeatureReferences(); for (int i = 0; i < irefs.length; i++) { IIncludedFeatureReference iref = irefs[i]; boolean preserve = false; if (iref.isOptional()) { boolean onTheList = false; for (int j = 0; j < optionalFeatures.length; j++) { if (optionalFeatures[j].equals(iref)) { //was on the list onTheList = true; break; } } if (!onTheList) preserve = true; } if (preserve) { try { String id = iref.getVersionedIdentifier().getIdentifier(); UpdateUI.setOriginatingURL(id, url); } catch (CoreException e) { // Silently ignore } } else { try { IFeature ifeature = iref.getFeature(null); preserveOriginatingURLs(ifeature, optionalFeatures); } catch (CoreException e) { // Silently ignore } } } } catch (CoreException e) { // Silently ignore } } /* (non-Javadoc) * @see org.eclipse.update.operations.IOperationListener#afterExecute(org.eclipse.update.operations.IOperation) */ public boolean afterExecute(IOperation operation, Object data) { if (!(operation instanceof IInstallFeatureOperation)) return true; IInstallFeatureOperation job = (IInstallFeatureOperation) operation; IFeature oldFeature = job.getOldFeature(); if (oldFeature == null && job.getOptionalFeatures() != null) preserveOriginatingURLs( job.getFeature(), job.getOptionalFeatures()); installCount++; return true; } /* (non-Javadoc) * @see org.eclipse.update.operations.IOperationListener#beforeExecute(org.eclipse.update.operations.IOperation) */ public boolean beforeExecute(IOperation operation, Object data) { return true; } /* (non-Javadoc) * @see org.eclipse.update.internal.ui.wizards.ISearchProvider2#getSearchRequest() */ public UpdateSearchRequest getSearchRequest() { return searchRequest; } public static synchronized boolean isRunning() { return isRunning || Platform.getJobManager().find(jobFamily).length > 0; } private IBatchOperation getBatchInstallOperation(final IInstallFeatureOperation[] selectedJobs) { final IVerificationListener verificationListener =new JarVerificationService( //InstallWizard.this.getShell()); UpdateUI.getActiveWorkbenchShell()); // setup jobs with the correct environment IInstallFeatureOperation[] operations = new IInstallFeatureOperation[selectedJobs.length]; for (int i = 0; i < selectedJobs.length; i++) { IInstallFeatureOperation job = selectedJobs[i]; IFeature[] unconfiguredOptionalFeatures = null; IFeatureReference[] optionalFeatures = null; if (UpdateUtils.hasOptionalFeatures(job.getFeature())) { optionalFeatures = optionalFeaturesPage.getCheckedOptionalFeatures(job); unconfiguredOptionalFeatures = optionalFeaturesPage.getUnconfiguredOptionalFeatures(job, job.getTargetSite()); } IInstallFeatureOperation op = OperationsManager .getOperationFactory() .createInstallOperation( job.getTargetSite(), job.getFeature(), optionalFeatures, unconfiguredOptionalFeatures, verificationListener); operations[i] = op; } return OperationsManager.getOperationFactory().createBatchInstallOperation(operations); } private void launchInBackground() { // Downloads the feature content in the background. // The job listener will then install the feature when download is finished. // TODO: should we cancel existing jobs? if (jobListener != null) Platform.getJobManager().removeJobChangeListener(jobListener); if (job != null) Platform.getJobManager().cancel(job); jobListener = new UpdateJobChangeListener(); Platform.getJobManager().addJobChangeListener(jobListener); job = new Job(UpdateUIMessages.InstallWizard_jobName) { public IStatus run(IProgressMonitor monitor) { if (download(monitor)) return Status.OK_STATUS; else { isRunning = false; return Status.CANCEL_STATUS; } } public boolean belongsTo(Object family) { return InstallWizard2.jobFamily == family; } }; job.setUser(true); job.setPriority(Job.INTERACTIVE); // if (wait) { // progressService.showInDialog(workbench.getActiveWorkbenchWindow().getShell(), job); // } job.schedule(); } private boolean install(IProgressMonitor monitor) { // Installs the (already downloaded) features and prompts for restart try { needsRestart = installOperation.execute(monitor, InstallWizard2.this); UpdateUI.getStandardDisplay().asyncExec(new Runnable() { public void run() { UpdateUI.requestRestart(InstallWizard2.this.isRestartNeeded()); } }); } catch (final InvocationTargetException e) { final Throwable targetException = e.getTargetException(); if (!(targetException instanceof InstallAbortedException)){ UpdateUI.getStandardDisplay().syncExec(new Runnable() { public void run() { UpdateUI.logException(targetException); } }); } return false; } catch (CoreException e) { return false; } finally { isRunning = false; } return true; } private boolean download(final IProgressMonitor monitor) { // Downloads the feature content. // This method is called from a background job. // If download fails, the user is prompted to retry. try { IFeatureOperation[] ops = installOperation.getOperations(); monitor.beginTask(UpdateUIMessages.InstallWizard_download, 3*ops.length); for (int i=0; i<ops.length; i++) { IInstallFeatureOperation op = (IInstallFeatureOperation)ops[i]; SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 3); try { if (op.getFeature() instanceof LiteFeature) { ISiteFeatureReference featureReference = getFeatureReference(op.getFeature()); IFeature feature = featureReference.getFeature(null); if (op instanceof InstallOperation) { ((InstallOperation)op).setFeature(feature); } } UpdateUtils.downloadFeatureContent(op.getTargetSite(), op.getFeature(), op.getOptionalFeatures(), subMonitor); } catch (final CoreException e) { if(e instanceof FeatureDownloadException){ boolean retry = retryDownload((FeatureDownloadException)e); if (retry) { // redownload current feature i--; continue; } } else { UpdateCore.log(e); if ( !monitor.isCanceled()) { Display.getDefault().syncExec( new Runnable () { public void run() { IStatus status = new Status( IStatus.ERROR, UpdateUI.getPluginId(), IStatus.OK, UpdateUIMessages.InstallWizard2_updateOperationHasFailed, null); ErrorDialog.openError(null, null, null, status); } }); } } return false; } } return true; } finally { monitor.done(); } } private boolean retryDownload(final FeatureDownloadException e) { final boolean retry[] = new boolean[1]; UpdateUI.getStandardDisplay().syncExec(new Runnable() { public void run() { retry[0] = MessageDialog.openQuestion( UpdateUI.getActiveWorkbenchShell(), UpdateUIMessages.InstallWizard_retryTitle, e.getMessage()+"\n" //$NON-NLS-1$ + UpdateUIMessages.InstallWizard_retry); } }); return retry[0]; } private class UpdateJobChangeListener extends JobChangeAdapter { public void done(final IJobChangeEvent event) { // the job listener is triggered when the download job is done, and it proceeds // with the actual install if (event.getJob() == InstallWizard2.this.job && event.getResult() == Status.OK_STATUS) { Platform.getJobManager().removeJobChangeListener(this); Platform.getJobManager().cancel(job); Job installJob = new Job(UpdateUIMessages.InstallWizard_jobName) { public IStatus run(IProgressMonitor monitor) { - install(monitor); + //install(monitor); if (install(monitor)) { return Status.OK_STATUS; - } else { + } else { isRunning = false; return Status.CANCEL_STATUS; } } public boolean belongsTo(Object family) { return InstallWizard2.jobFamily == family; } }; installJob.setUser(true); installJob.setPriority(Job.INTERACTIVE); // if (wait) { // progressService.showInDialog(workbench.getActiveWorkbenchWindow().getShell(), job); // } installJob.schedule(); /*final IProgressService progressService= PlatformUI.getWorkbench().getProgressService(); UpdateUI.getStandardDisplay().asyncExec(new Runnable() { public void run() { try { progressService.busyCursorWhile( new IRunnableWithProgress() { public void run(final IProgressMonitor monitor){ install(monitor); } }); } catch (InvocationTargetException e) { UpdateUI.logException(e); } catch (InterruptedException e) { UpdateUI.logException(e, false); } } }); */ } else if (event.getJob() == InstallWizard2.this.job && event.getResult() != Status.OK_STATUS) { isRunning = false; Platform.getJobManager().removeJobChangeListener(this); Platform.getJobManager().cancel(job); UpdateUI.getStandardDisplay().syncExec(new Runnable() { public void run() { UpdateUI.log(event.getResult(), true); } }); } } } public ISiteFeatureReference getFeatureReference(IFeature feature) { ISite site = feature.getSite(); ISiteFeatureReference[] references = site.getFeatureReferences(); ISiteFeatureReference currentReference = null; for (int i = 0; i < references.length; i++) { currentReference = references[i]; try { if (feature.getVersionedIdentifier().equals(currentReference.getVersionedIdentifier())) return currentReference; } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } UpdateCore.warn("Feature " + feature + " not found on site" + site.getURL()); //$NON-NLS-1$ //$NON-NLS-2$ return null; } }
false
true
public void done(final IJobChangeEvent event) { // the job listener is triggered when the download job is done, and it proceeds // with the actual install if (event.getJob() == InstallWizard2.this.job && event.getResult() == Status.OK_STATUS) { Platform.getJobManager().removeJobChangeListener(this); Platform.getJobManager().cancel(job); Job installJob = new Job(UpdateUIMessages.InstallWizard_jobName) { public IStatus run(IProgressMonitor monitor) { install(monitor); if (install(monitor)) { return Status.OK_STATUS; } else { isRunning = false; return Status.CANCEL_STATUS; } } public boolean belongsTo(Object family) { return InstallWizard2.jobFamily == family; } }; installJob.setUser(true); installJob.setPriority(Job.INTERACTIVE); // if (wait) { // progressService.showInDialog(workbench.getActiveWorkbenchWindow().getShell(), job); // } installJob.schedule(); /*final IProgressService progressService= PlatformUI.getWorkbench().getProgressService(); UpdateUI.getStandardDisplay().asyncExec(new Runnable() { public void run() { try { progressService.busyCursorWhile( new IRunnableWithProgress() { public void run(final IProgressMonitor monitor){ install(monitor); } }); } catch (InvocationTargetException e) { UpdateUI.logException(e); } catch (InterruptedException e) { UpdateUI.logException(e, false); } } }); */ } else if (event.getJob() == InstallWizard2.this.job && event.getResult() != Status.OK_STATUS) { isRunning = false; Platform.getJobManager().removeJobChangeListener(this); Platform.getJobManager().cancel(job); UpdateUI.getStandardDisplay().syncExec(new Runnable() { public void run() { UpdateUI.log(event.getResult(), true); } }); } }
public void done(final IJobChangeEvent event) { // the job listener is triggered when the download job is done, and it proceeds // with the actual install if (event.getJob() == InstallWizard2.this.job && event.getResult() == Status.OK_STATUS) { Platform.getJobManager().removeJobChangeListener(this); Platform.getJobManager().cancel(job); Job installJob = new Job(UpdateUIMessages.InstallWizard_jobName) { public IStatus run(IProgressMonitor monitor) { //install(monitor); if (install(monitor)) { return Status.OK_STATUS; } else { isRunning = false; return Status.CANCEL_STATUS; } } public boolean belongsTo(Object family) { return InstallWizard2.jobFamily == family; } }; installJob.setUser(true); installJob.setPriority(Job.INTERACTIVE); // if (wait) { // progressService.showInDialog(workbench.getActiveWorkbenchWindow().getShell(), job); // } installJob.schedule(); /*final IProgressService progressService= PlatformUI.getWorkbench().getProgressService(); UpdateUI.getStandardDisplay().asyncExec(new Runnable() { public void run() { try { progressService.busyCursorWhile( new IRunnableWithProgress() { public void run(final IProgressMonitor monitor){ install(monitor); } }); } catch (InvocationTargetException e) { UpdateUI.logException(e); } catch (InterruptedException e) { UpdateUI.logException(e, false); } } }); */ } else if (event.getJob() == InstallWizard2.this.job && event.getResult() != Status.OK_STATUS) { isRunning = false; Platform.getJobManager().removeJobChangeListener(this); Platform.getJobManager().cancel(job); UpdateUI.getStandardDisplay().syncExec(new Runnable() { public void run() { UpdateUI.log(event.getResult(), true); } }); } }
diff --git a/osmorc/src/org/osmorc/i18n/OsmorcBundle.java b/osmorc/src/org/osmorc/i18n/OsmorcBundle.java index 80c70e9413..67c98208c9 100644 --- a/osmorc/src/org/osmorc/i18n/OsmorcBundle.java +++ b/osmorc/src/org/osmorc/i18n/OsmorcBundle.java @@ -1,152 +1,157 @@ /* * Copyright (c) 2007-2009, Osmorc Development Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of 'Osmorc Development Team' nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.osmorc.i18n; import com.intellij.CommonBundle; import com.intellij.openapi.util.IconLoader; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.PropertyKey; import javax.swing.*; import java.io.*; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.Map; import java.util.ResourceBundle; import java.util.WeakHashMap; /** * Internationalization bundle for Osmorc. * * @author <a href="mailto:[email protected]">Jan Thom&auml;</a> * @version $Id$ */ public class OsmorcBundle { private static Reference<ResourceBundle> _ourBundle; private static String infoHtml; private static Map<String, Icon> _iconCache = new WeakHashMap<String, Icon>(); @NonNls private static final String BUNDLE = "org.osmorc.i18n.OsmorcBundle"; private OsmorcBundle() { } /** * Translates the given message. * * @param key the key to be used for translation * @param params the parameters for the translation * @return the translated message. */ public static String getTranslation(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { return CommonBundle.message(getBundle(), key, params); } /** * Returns the resource bundle. In case there is a memory shortage the resource bundle is garbage collected. This * method will provide a new resource bundle in case the previous one got garbage collected. * * @return the resoruce bundle. */ private static ResourceBundle getBundle() { ResourceBundle bundle = null; if (_ourBundle != null) { bundle = _ourBundle.get(); } if (bundle == null) { bundle = ResourceBundle.getBundle(BUNDLE); _ourBundle = new SoftReference<ResourceBundle>(bundle); } return bundle; } private static Icon getCachedIcon(@PropertyKey(resourceBundle = OsmorcBundle.BUNDLE) String property) { Icon result = _iconCache.get(property); if (result == null) { result = IconLoader.getIcon(getTranslation(property)); _iconCache.put(property, result); } return result; } /** * @return a small icon for Osmorc */ public static Icon getSmallIcon() { return getCachedIcon("runconfiguration.icon"); } /** * @return a big icon for Osmorc */ public static Icon getBigIcon() { return getCachedIcon("projectconfiguration.icon"); } public static Icon getLogo() { return getCachedIcon("logo.icon"); } public static String getInfo() { if (infoHtml == null) { - StringBuffer buffer = new StringBuffer(); - FileReader reader = null; + StringBuilder builder = new StringBuilder(); + InputStream stream = null; + InputStreamReader streamReader = null; BufferedReader bReader = null; try { String infoFileName = getTranslation("info.file"); - reader = new FileReader(OsmorcBundle.class.getResource(infoFileName).getFile()); - bReader = new BufferedReader(reader); + stream = OsmorcBundle.class.getResourceAsStream(infoFileName); + streamReader = new InputStreamReader(stream); + bReader = new BufferedReader(streamReader); while (bReader.ready()) { - buffer.append(bReader.readLine()); + builder.append(bReader.readLine()); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (bReader != null) { bReader.close(); } - if (reader != null) { - reader.close(); + if (streamReader != null) { + streamReader.close(); + } + if (stream != null) { + stream.close(); } } catch (IOException e) { throw new RuntimeException(e); } } - infoHtml = buffer.toString(); + infoHtml = builder.toString(); } return infoHtml; } }
false
true
public static String getInfo() { if (infoHtml == null) { StringBuffer buffer = new StringBuffer(); FileReader reader = null; BufferedReader bReader = null; try { String infoFileName = getTranslation("info.file"); reader = new FileReader(OsmorcBundle.class.getResource(infoFileName).getFile()); bReader = new BufferedReader(reader); while (bReader.ready()) { buffer.append(bReader.readLine()); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (bReader != null) { bReader.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { throw new RuntimeException(e); } } infoHtml = buffer.toString(); } return infoHtml; }
public static String getInfo() { if (infoHtml == null) { StringBuilder builder = new StringBuilder(); InputStream stream = null; InputStreamReader streamReader = null; BufferedReader bReader = null; try { String infoFileName = getTranslation("info.file"); stream = OsmorcBundle.class.getResourceAsStream(infoFileName); streamReader = new InputStreamReader(stream); bReader = new BufferedReader(streamReader); while (bReader.ready()) { builder.append(bReader.readLine()); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (bReader != null) { bReader.close(); } if (streamReader != null) { streamReader.close(); } if (stream != null) { stream.close(); } } catch (IOException e) { throw new RuntimeException(e); } } infoHtml = builder.toString(); } return infoHtml; }
diff --git a/src/edu/jas/poly/GenPolynomialTokenizer.java b/src/edu/jas/poly/GenPolynomialTokenizer.java index 05478291..9c15e5d6 100644 --- a/src/edu/jas/poly/GenPolynomialTokenizer.java +++ b/src/edu/jas/poly/GenPolynomialTokenizer.java @@ -1,1497 +1,1497 @@ /* * $Id$ */ package edu.jas.poly; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.Scanner; import org.apache.log4j.Logger; import edu.jas.arith.BigComplex; import edu.jas.arith.BigDecimal; import edu.jas.arith.BigInteger; import edu.jas.arith.BigQuaternion; import edu.jas.arith.BigRational; import edu.jas.arith.ModInteger; import edu.jas.arith.ModIntegerRing; import edu.jas.arith.ModLongRing; import edu.jas.structure.Power; import edu.jas.structure.RingElem; import edu.jas.structure.RingFactory; /** * GenPolynomial Tokenizer. Used to read rational polynomials and lists of * polynomials from input streams. Arbitrary polynomial rings and coefficient * rings can be read with RingFactoryTokenizer. <b>Note:</b> Can no more read * QuotientRing since end of 2010, revision 3441. Quotient coefficients and * others can still be read if the respective factory is provided via the * constructor. * @see edu.jas.application.RingFactoryTokenizer * @author Heinz Kredel */ public class GenPolynomialTokenizer { private static final Logger logger = Logger.getLogger(GenPolynomialTokenizer.class); private final boolean debug = logger.isDebugEnabled(); private String[] vars; private int nvars = 1; private TermOrder tord; private RelationTable table; //private Reader in; private final StreamTokenizer tok; private final Reader reader; private RingFactory fac; private static enum coeffType { BigRat, BigInt, ModInt, BigC, BigQ, BigD, ANrat, ANmod, IntFunc }; private coeffType parsedCoeff = coeffType.BigRat; private GenPolynomialRing pfac; private static enum polyType { PolBigRat, PolBigInt, PolModInt, PolBigC, PolBigD, PolBigQ, PolANrat, PolANmod, PolIntFunc }; private polyType parsedPoly = polyType.PolBigRat; private GenSolvablePolynomialRing spfac; /** * noargs constructor reads from System.in. */ public GenPolynomialTokenizer() { this(new BufferedReader(new InputStreamReader(System.in))); } /** * constructor with Ring and Reader. * @param rf ring factory. * @param r reader stream. */ public GenPolynomialTokenizer(GenPolynomialRing rf, Reader r) { this(r); if (rf == null) { return; } if (rf instanceof GenSolvablePolynomialRing) { pfac = rf; spfac = (GenSolvablePolynomialRing) rf; } else { pfac = rf; spfac = null; } fac = rf.coFac; vars = rf.vars; if (vars != null) { nvars = vars.length; } tord = rf.tord; // relation table if (spfac != null) { table = spfac.table; } else { table = null; } } /** * constructor with Reader. * @param r reader stream. */ @SuppressWarnings("unchecked") public GenPolynomialTokenizer(Reader r) { //BasicConfigurator.configure(); vars = null; tord = new TermOrder(); nvars = 1; fac = new BigRational(1); pfac = new GenPolynomialRing<BigRational>(fac, nvars, tord, vars); spfac = new GenSolvablePolynomialRing<BigRational>(fac, nvars, tord, vars); reader = r; tok = new StreamTokenizer(r); tok.resetSyntax(); // tok.eolIsSignificant(true); no more tok.eolIsSignificant(false); tok.wordChars('0', '9'); tok.wordChars('a', 'z'); tok.wordChars('A', 'Z'); tok.wordChars('_', '_'); // for subscripts x_i tok.wordChars('/', '/'); // wg. rational numbers tok.wordChars(128 + 32, 255); tok.whitespaceChars(0, ' '); tok.commentChar('#'); tok.quoteChar('"'); tok.quoteChar('\''); //tok.slashStarComments(true); does not work } /** * Initialize coefficient and polynomial factories. * @param rf ring factory. * @param ct coefficient type. */ @SuppressWarnings("unchecked") public void initFactory(RingFactory rf, coeffType ct) { fac = rf; parsedCoeff = ct; switch (ct) { case BigRat: pfac = new GenPolynomialRing<BigRational>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigRat; break; case BigInt: pfac = new GenPolynomialRing<BigInteger>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigInt; break; case ModInt: pfac = new GenPolynomialRing<ModInteger>(fac, nvars, tord, vars); parsedPoly = polyType.PolModInt; break; case BigC: pfac = new GenPolynomialRing<BigComplex>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigC; break; case BigQ: pfac = new GenPolynomialRing<BigQuaternion>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigQ; break; case BigD: pfac = new GenPolynomialRing<BigDecimal>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigD; break; case IntFunc: pfac = new GenPolynomialRing<GenPolynomial<BigRational>>(fac, nvars, tord, vars); parsedPoly = polyType.PolIntFunc; break; default: pfac = new GenPolynomialRing<BigRational>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigRat; } } /** * Initialize polynomial and solvable polynomial factories. * @param rf ring factory. * @param ct coefficient type. */ @SuppressWarnings("unchecked") public void initSolvableFactory(RingFactory rf, coeffType ct) { fac = rf; parsedCoeff = ct; switch (ct) { case BigRat: spfac = new GenSolvablePolynomialRing<BigRational>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigRat; break; case BigInt: spfac = new GenSolvablePolynomialRing<BigInteger>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigInt; break; case ModInt: spfac = new GenSolvablePolynomialRing<ModInteger>(fac, nvars, tord, vars); parsedPoly = polyType.PolModInt; break; case BigC: spfac = new GenSolvablePolynomialRing<BigComplex>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigC; break; case BigQ: spfac = new GenSolvablePolynomialRing<BigQuaternion>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigQ; break; case BigD: spfac = new GenSolvablePolynomialRing<BigDecimal>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigD; break; case IntFunc: spfac = new GenSolvablePolynomialRing<GenPolynomial<BigRational>>(fac, nvars, tord, vars); parsedPoly = polyType.PolIntFunc; break; default: spfac = new GenSolvablePolynomialRing<BigRational>(fac, nvars, tord, vars); parsedPoly = polyType.PolBigRat; } } /** * Parsing method for GenPolynomial. syntax ? (simple) * @return the next polynomial. * @throws IOException */ @SuppressWarnings("unchecked") public GenPolynomial nextPolynomial() throws IOException { if (debug) { logger.debug("torder = " + tord); } GenPolynomial a = pfac.getZERO(); GenPolynomial a1 = pfac.getONE(); ExpVector leer = pfac.evzero; if (debug) { logger.debug("a = " + a); logger.debug("a1 = " + a1); } GenPolynomial b = a1; GenPolynomial c; int tt; //, oldtt; //String rat = ""; char first; RingElem r; ExpVector e; int ix; long ie; boolean done = false; while (!done) { // next input. determine next action tt = tok.nextToken(); //System.out.println("while tt = " + tok); logger.debug("while tt = " + tok); if (tt == StreamTokenizer.TT_EOF) break; switch (tt) { case ')': case ',': return a; // do not change or remove case '-': b = b.negate(); case '+': case '*': tt = tok.nextToken(); break; default: // skip } // read coefficient, monic monomial and polynomial if (tt == StreamTokenizer.TT_EOF) break; switch (tt) { // case '_': removed case '}': throw new InvalidExpressionException("mismatch of braces after " + a + ", error at " + b); case '{': // recursion StringBuffer rf = new StringBuffer(); int level = 0; do { tt = tok.nextToken(); //System.out.println("token { = " + ((char)tt) + ", " + tt + ", level = " + level); if (tt == StreamTokenizer.TT_EOF) { throw new InvalidExpressionException("mismatch of braces after " + a + ", error at " + b); } if (tt == '{') { level++; } if (tt == '}') { level--; if (level < 0) { continue; // skip last closing brace } } if (tok.sval != null) { if (rf.length() > 0 && rf.charAt(rf.length() - 1) != '.') { rf.append(" "); } rf.append(tok.sval); // " " + } else { rf.append((char) tt); } } while (level >= 0); //System.out.println("coeff{} = " + rf.toString() ); try { r = (RingElem) fac.parse(rf.toString()); } catch (NumberFormatException re) { throw new InvalidExpressionException("not a number " + rf, re); } if (debug) logger.debug("coeff " + r); ie = nextExponent(); if (debug) logger.debug("ie " + ie); r = Power.<RingElem> positivePower(r, ie); if (debug) logger.debug("coeff^ie " + r); b = b.multiply(r, leer); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); //no break; break; case StreamTokenizer.TT_WORD: //System.out.println("TT_WORD: " + tok.sval); if (tok.sval == null || tok.sval.length() == 0) break; // read coefficient first = tok.sval.charAt(0); if (digit(first)) { //System.out.println("coeff 0 = " + tok.sval ); StringBuffer df = new StringBuffer(); df.append(tok.sval); tt = tok.nextToken(); if (tt == '.') { tt = tok.nextToken(); if (debug) logger.debug("tt,dot = " + tok); if (tok.sval != null) { df.append("."); df.append(tok.sval); } else { tok.pushBack(); tok.pushBack(); } } else { tok.pushBack(); } try { r = (RingElem) fac.parse(df.toString()); } catch (NumberFormatException re) { throw new InvalidExpressionException("not a number " + df, re); } if (debug) logger.debug("coeff " + r); //System.out.println("r = " + r.toScriptFactory()); ie = nextExponent(); if (debug) logger.debug("ie " + ie); // r = r^ie; r = Power.<RingElem> positivePower(r, ie); if (debug) logger.debug("coeff^ie " + r); b = b.multiply(r, leer); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); } if (tt == StreamTokenizer.TT_EOF) break; if (tok.sval == null) break; // read monomial or recursion first = tok.sval.charAt(0); if (letter(first)) { ix = leer.indexVar(tok.sval, vars); //indexVar( tok.sval ); if (ix < 0) { // not found try { r = (RingElem) fac.parse(tok.sval); } catch (NumberFormatException re) { throw new InvalidExpressionException("recursively unknown variable " + tok.sval); } if (debug) logger.info("coeff " + r); - if (r.isONE() || r.isZERO()) { + //if (r.isONE() || r.isZERO()) { //logger.error("Unknown varibable " + tok.sval); //done = true; //break; - throw new InvalidExpressionException("recursively unknown variable " + tok.sval); - } + //throw new InvalidExpressionException("recursively unknown variable " + tok.sval); + //} ie = nextExponent(); // System.out.println("ie: " + ie); r = Power.<RingElem> positivePower(r, ie); b = b.multiply(r); } else { // found // System.out.println("ix: " + ix); ie = nextExponent(); // System.out.println("ie: " + ie); e = ExpVector.create(vars.length, ix, ie); b = b.multiply(e); } tt = tok.nextToken(); if (debug) logger.debug("tt,letter = " + tok); } break; case '(': c = nextPolynomial(); if (debug) logger.debug("factor " + c); ie = nextExponent(); if (debug) logger.debug("ie " + ie); c = Power.<GenPolynomial> positivePower(c, ie); if (debug) logger.debug("factor^ie " + c); b = b.multiply(c); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); //no break; break; default: //skip } if (done) break; // unknown variable if (tt == StreamTokenizer.TT_EOF) break; // complete polynomial tok.pushBack(); switch (tt) { case '-': case '+': case ')': case ',': logger.debug("b, = " + b); a = a.sum(b); b = a1; break; case '*': logger.debug("b, = " + b); //a = a.sum(b); //b = a1; break; case '\n': tt = tok.nextToken(); if (debug) logger.debug("tt,nl = " + tt); default: // skip or finish ? if (debug) logger.debug("default: " + tok); } } if (debug) logger.debug("b = " + b); a = a.sum(b); logger.debug("a = " + a); // b = a1; return a; } /** * Parsing method for exponent (of variable). syntax: ^long | **long. * @return the next exponent or 1. * @throws IOException */ public long nextExponent() throws IOException { long e = 1; char first; int tt; tt = tok.nextToken(); if (tt == '^') { if (debug) logger.debug("exponent ^"); tt = tok.nextToken(); if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { e = Long.parseLong(tok.sval); return e; } } } if (tt == '*') { tt = tok.nextToken(); if (tt == '*') { if (debug) logger.debug("exponent **"); tt = tok.nextToken(); if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { e = Long.parseLong(tok.sval); return e; } } } tok.pushBack(); } tok.pushBack(); return e; } /** * Parsing method for comments. syntax: (* comment *) | /_* comment *_/ * without _ Does not work with this pushBack(), unused. */ public String nextComment() throws IOException { // syntax: (* comment *) | /* comment */ StringBuffer c = new StringBuffer(); int tt; if (debug) logger.debug("comment: " + tok); tt = tok.nextToken(); if (debug) logger.debug("comment: " + tok); if (tt == '(') { tt = tok.nextToken(); if (debug) logger.debug("comment: " + tok); if (tt == '*') { if (debug) logger.debug("comment: "); while (true) { tt = tok.nextToken(); if (tt == '*') { tt = tok.nextToken(); if (tt == ')') { return c.toString(); } tok.pushBack(); } c.append(tok.sval); } } tok.pushBack(); if (debug) logger.debug("comment: " + tok); } tok.pushBack(); if (debug) logger.debug("comment: " + tok); return c.toString(); } /** * Parsing method for variable list. syntax: (a, b c, de) gives [ "a", "b", * "c", "de" ] * @return the next variable list. * @throws IOException */ public String[] nextVariableList() throws IOException { List<String> l = new ArrayList<String>(); int tt; tt = tok.nextToken(); //System.out.println("vList tok = " + tok); if (tt == '(' || tt == '{') { logger.debug("variable list"); tt = tok.nextToken(); while (true) { if (tt == StreamTokenizer.TT_EOF) break; if (tt == ')' || tt == '}') break; if (tt == StreamTokenizer.TT_WORD) { //System.out.println("TT_WORD: " + tok.sval); l.add(tok.sval); } tt = tok.nextToken(); } } Object[] ol = l.toArray(); String[] v = new String[ol.length]; for (int i = 0; i < v.length; i++) { v[i] = (String) ol[i]; } return v; } /** * Parsing method for coefficient ring. syntax: Rat | Q | Int | Z | Mod * modul | Complex | C | D | Quat | AN[ (var) ( poly ) | AN[ modul (var) ( * poly ) ] | IntFunc (var_list) * @return the next coefficient factory. * @throws IOException */ @SuppressWarnings("unchecked") public RingFactory nextCoefficientRing() throws IOException { RingFactory coeff = null; coeffType ct = null; int tt; tt = tok.nextToken(); if (tok.sval != null) { if (tok.sval.equalsIgnoreCase("Q")) { coeff = new BigRational(0); ct = coeffType.BigRat; } else if (tok.sval.equalsIgnoreCase("Rat")) { coeff = new BigRational(0); ct = coeffType.BigRat; } else if (tok.sval.equalsIgnoreCase("D")) { coeff = new BigDecimal(0); ct = coeffType.BigD; } else if (tok.sval.equalsIgnoreCase("Z")) { coeff = new BigInteger(0); ct = coeffType.BigInt; } else if (tok.sval.equalsIgnoreCase("Int")) { coeff = new BigInteger(0); ct = coeffType.BigInt; } else if (tok.sval.equalsIgnoreCase("C")) { coeff = new BigComplex(0); ct = coeffType.BigC; } else if (tok.sval.equalsIgnoreCase("Complex")) { coeff = new BigComplex(0); ct = coeffType.BigC; } else if (tok.sval.equalsIgnoreCase("Quat")) { coeff = new BigQuaternion(0); ct = coeffType.BigQ; } else if (tok.sval.equalsIgnoreCase("Mod")) { tt = tok.nextToken(); boolean openb = false; if (tt == '[') { // optional openb = true; tt = tok.nextToken(); } if (tok.sval != null && tok.sval.length() > 0) { if (digit(tok.sval.charAt(0))) { BigInteger mo = new BigInteger(tok.sval); BigInteger lm = new BigInteger(Long.MAX_VALUE); if (mo.compareTo(lm) < 0) { coeff = new ModLongRing(mo.getVal()); } else { coeff = new ModIntegerRing(mo.getVal()); } //System.out.println("coeff = " + coeff + " :: " + coeff.getClass()); ct = coeffType.ModInt; } else { tok.pushBack(); } } else { tok.pushBack(); } if (tt == ']' && openb) { // optional tt = tok.nextToken(); } } else if (tok.sval.equalsIgnoreCase("RatFunc") || tok.sval.equalsIgnoreCase("ModFunc")) { //logger.error("RatFunc and ModFunc can no more be read, see edu.jas.application.RingFactoryTokenizer."); throw new InvalidExpressionException( "RatFunc and ModFunc can no more be read, see edu.jas.application.RingFactoryTokenizer."); } else if (tok.sval.equalsIgnoreCase("IntFunc")) { String[] rfv = nextVariableList(); //System.out.println("rfv = " + rfv.length + " " + rfv[0]); int vr = rfv.length; BigRational bi = new BigRational(); TermOrder to = new TermOrder(TermOrder.INVLEX); GenPolynomialRing<BigRational> pcf = new GenPolynomialRing<BigRational>(bi, vr, to, rfv); coeff = pcf; ct = coeffType.IntFunc; } else if (tok.sval.equalsIgnoreCase("AN")) { tt = tok.nextToken(); if (tt == '[') { tt = tok.nextToken(); RingFactory tcfac = new ModIntegerRing("19"); if (tok.sval != null && tok.sval.length() > 0) { if (digit(tok.sval.charAt(0))) { tcfac = new ModIntegerRing(tok.sval); } else { tcfac = new BigRational(); tok.pushBack(); } } else { tcfac = new BigRational(); tok.pushBack(); } String[] anv = nextVariableList(); //System.out.println("anv = " + anv.length + " " + anv[0]); int vs = anv.length; if (vs != 1) { throw new InvalidExpressionException( "AlgebraicNumber only for univariate polynomials " + Arrays.toString(anv)); } String[] ovars = vars; vars = anv; GenPolynomialRing tpfac = pfac; RingFactory tfac = fac; fac = tcfac; // pfac and fac used in nextPolynomial() if (tcfac instanceof ModIntegerRing) { pfac = new GenPolynomialRing<ModInteger>(tcfac, vs, new TermOrder(), anv); } else { pfac = new GenPolynomialRing<BigRational>(tcfac, vs, new TermOrder(), anv); } if (debug) { logger.debug("pfac = " + pfac); } tt = tok.nextToken(); GenPolynomial mod; if (tt == '(') { mod = nextPolynomial(); tt = tok.nextToken(); if (tok.ttype != ')') tok.pushBack(); } else { tok.pushBack(); mod = nextPolynomial(); } if (debug) { logger.debug("mod = " + mod); } pfac = tpfac; fac = tfac; vars = ovars; if (tcfac instanceof ModIntegerRing) { GenPolynomial<ModInteger> gfmod; gfmod = (GenPolynomial<ModInteger>) mod; coeff = new AlgebraicNumberRing<ModInteger>(gfmod); ct = coeffType.ANmod; } else { GenPolynomial<BigRational> anmod; anmod = (GenPolynomial<BigRational>) mod; coeff = new AlgebraicNumberRing<BigRational>(anmod); ct = coeffType.ANrat; } if (debug) { logger.debug("coeff = " + coeff); } tt = tok.nextToken(); if (tt == ']') { //ok, no nextToken(); } else { tok.pushBack(); } } else { tok.pushBack(); } } } if (coeff == null) { tok.pushBack(); coeff = new BigRational(); ct = coeffType.BigRat; } parsedCoeff = ct; return coeff; } /** * Parsing method for weight list. syntax: (w1, w2, w3, ..., wn) * @return the next weight list. * @throws IOException */ public long[] nextWeightList() throws IOException { List<Long> l = new ArrayList<Long>(); long[] w = null; long e; char first; int tt; tt = tok.nextToken(); if (tt == '(') { logger.debug("weight list"); tt = tok.nextToken(); while (true) { if (tt == StreamTokenizer.TT_EOF) break; if (tt == ')') break; if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { e = Long.parseLong(tok.sval); l.add(new Long(e)); //System.out.println("w: " + e); } } tt = tok.nextToken(); // also comma } } Object[] ol = l.toArray(); w = new long[ol.length]; for (int i = 0; i < w.length; i++) { w[i] = ((Long) ol[ol.length - i - 1]).longValue(); } return w; } /** * Parsing method for weight array. syntax: ( (w11, ...,w1n), ..., (wm1, * ..., wmn) ) * @return the next weight array. * @throws IOException */ public long[][] nextWeightArray() throws IOException { List<long[]> l = new ArrayList<long[]>(); long[][] w = null; long[] e; char first; int tt; tt = tok.nextToken(); if (tt == '(') { logger.debug("weight array"); tt = tok.nextToken(); while (true) { if (tt == StreamTokenizer.TT_EOF) break; if (tt == ')') break; if (tt == '(') { tok.pushBack(); e = nextWeightList(); l.add(e); //System.out.println("wa: " + e); } else if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { tok.pushBack(); tok.pushBack(); e = nextWeightList(); l.add(e); break; //System.out.println("w: " + e); } } tt = tok.nextToken(); // also comma } } Object[] ol = l.toArray(); w = new long[ol.length][]; for (int i = 0; i < w.length; i++) { w[i] = (long[]) ol[i]; } return w; } /** * Parsing method for split index. syntax: |i| * @return the next split index. * @throws IOException */ public int nextSplitIndex() throws IOException { int e = -1; // =unknown int e0 = -1; // =unknown char first; int tt; tt = tok.nextToken(); if (tt == '|') { logger.debug("split index"); tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) { return e; } if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { e = Integer.parseInt(tok.sval); //System.out.println("w: " + i); } tt = tok.nextToken(); if (tt != '|') { tok.pushBack(); } } } else if (tt == '[') { logger.debug("split index"); tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) { return e; } if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { e0 = Integer.parseInt(tok.sval); //System.out.println("w: " + i); } tt = tok.nextToken(); if (tt == ',') { tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) { return e; } if (tok.sval != null) { first = tok.sval.charAt(0); if (digit(first)) { e = Integer.parseInt(tok.sval); //System.out.println("w: " + i); } } if (tt != ']') { tok.pushBack(); } } } } else { tok.pushBack(); } return e; } /** * Parsing method for term order name. syntax: termOrderName = L, IL, LEX, * G, IG, GRLEX, W(weights) |split index| * @return the next term order. * @throws IOException */ public TermOrder nextTermOrder() throws IOException { int evord = TermOrder.DEFAULT_EVORD; int tt; tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) { /* nop */ } if (tt == StreamTokenizer.TT_WORD) { // System.out.println("TT_WORD: " + tok.sval); if (tok.sval != null) { if (tok.sval.equalsIgnoreCase("L")) { evord = TermOrder.INVLEX; } else if (tok.sval.equalsIgnoreCase("IL")) { evord = TermOrder.INVLEX; } else if (tok.sval.equalsIgnoreCase("INVLEX")) { evord = TermOrder.INVLEX; } else if (tok.sval.equalsIgnoreCase("LEX")) { evord = TermOrder.LEX; } else if (tok.sval.equalsIgnoreCase("G")) { evord = TermOrder.IGRLEX; } else if (tok.sval.equalsIgnoreCase("IG")) { evord = TermOrder.IGRLEX; } else if (tok.sval.equalsIgnoreCase("IGRLEX")) { evord = TermOrder.IGRLEX; } else if (tok.sval.equalsIgnoreCase("GRLEX")) { evord = TermOrder.GRLEX; } else if (tok.sval.equalsIgnoreCase("W")) { long[][] w = nextWeightArray(); //int s = nextSplitIndex(); // no more return new TermOrder(w); } } } int s = nextSplitIndex(); if (s <= 0) { return new TermOrder(evord); } return new TermOrder(evord, evord, vars.length, s); } /** * Parsing method for polynomial list. syntax: ( p1, p2, p3, ..., pn ) * @return the next polynomial list. * @throws IOException */ public List<GenPolynomial> nextPolynomialList() throws IOException { GenPolynomial a; List<GenPolynomial> L = new ArrayList<GenPolynomial>(); int tt; tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) return L; if (tt != '(') return L; logger.debug("polynomial list"); while (true) { tt = tok.nextToken(); if (tok.ttype == ',') continue; if (tt == '(') { a = nextPolynomial(); tt = tok.nextToken(); if (tok.ttype != ')') tok.pushBack(); } else { tok.pushBack(); a = nextPolynomial(); } logger.info("next pol = " + a); L.add(a); if (tok.ttype == StreamTokenizer.TT_EOF) break; if (tok.ttype == ')') break; } return L; } /** * Parsing method for submodule list. syntax: ( ( p11, p12, p13, ..., p1n ), * ..., ( pm1, pm2, pm3, ..., pmn ) ) * @return the next list of polynomial lists. * @throws IOException */ public List<List<GenPolynomial>> nextSubModuleList() throws IOException { List<List<GenPolynomial>> L = new ArrayList<List<GenPolynomial>>(); int tt; tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) return L; if (tt != '(') return L; logger.debug("module list"); List<GenPolynomial> v = null; while (true) { tt = tok.nextToken(); if (tok.ttype == ',') continue; if (tok.ttype == ')') break; if (tok.ttype == StreamTokenizer.TT_EOF) break; if (tt == '(') { tok.pushBack(); v = nextPolynomialList(); logger.info("next vect = " + v); L.add(v); } } return L; } /** * Parsing method for solvable polynomial relation table. syntax: ( p_1, * p_2, p_3, ..., p_{n+3} ) semantics: p_{n+1} * p_{n+2} = p_{n+3} The next * relation table is stored into the solvable polynomial factory. * @throws IOException */ @SuppressWarnings("unchecked") public void nextRelationTable() throws IOException { if (spfac == null) { return; } RelationTable table = spfac.table; List<GenPolynomial> rels = null; GenPolynomial p; GenSolvablePolynomial sp; int tt; tt = tok.nextToken(); if (tok.sval != null) { if (tok.sval.equalsIgnoreCase("RelationTable")) { rels = nextPolynomialList(); } } if (rels == null) { tok.pushBack(); return; } for (Iterator<GenPolynomial> it = rels.iterator(); it.hasNext();) { p = it.next(); ExpVector e = p.leadingExpVector(); if (it.hasNext()) { p = it.next(); ExpVector f = p.leadingExpVector(); if (it.hasNext()) { p = it.next(); sp = new GenSolvablePolynomial(spfac, p.val); table.update(e, f, sp); } } } if (debug) { logger.info("table = " + table); } return; } /** * Parsing method for polynomial set. syntax: coeffRing varList * termOrderName polyList. * @return the next polynomial set. * @throws IOException */ @SuppressWarnings("unchecked") public PolynomialList nextPolynomialSet() throws IOException { //String comments = ""; //comments += nextComment(); //if (debug) logger.debug("comment = " + comments); RingFactory coeff = nextCoefficientRing(); logger.info("coeff = " + coeff); vars = nextVariableList(); String dd = "vars ="; for (int i = 0; i < vars.length; i++) { dd += " " + vars[i]; } logger.info(dd); if (vars != null) { nvars = vars.length; } tord = nextTermOrder(); logger.info("tord = " + tord); // check more TOs initFactory(coeff, parsedCoeff); // global: nvars, tord, vars List<GenPolynomial> s = null; s = nextPolynomialList(); logger.info("s = " + s); // comments += nextComment(); return new PolynomialList(pfac, s); } /** * Parsing method for module set. syntax: coeffRing varList termOrderName * moduleList. * @return the next module set. * @throws IOException */ @SuppressWarnings("unchecked") public ModuleList nextSubModuleSet() throws IOException { //String comments = ""; //comments += nextComment(); //if (debug) logger.debug("comment = " + comments); RingFactory coeff = nextCoefficientRing(); logger.info("coeff = " + coeff); vars = nextVariableList(); String dd = "vars ="; for (int i = 0; i < vars.length; i++) { dd += " " + vars[i]; } logger.info(dd); if (vars != null) { nvars = vars.length; } tord = nextTermOrder(); logger.info("tord = " + tord); // check more TOs initFactory(coeff, parsedCoeff); // global: nvars, tord, vars List<List<GenPolynomial>> m = null; m = nextSubModuleList(); logger.info("m = " + m); // comments += nextComment(); return new ModuleList(pfac, m); } /** * Parsing method for solvable polynomial list. syntax: ( p1, p2, p3, ..., * pn ) * @return the next solvable polynomial list. * @throws IOException */ @SuppressWarnings("unchecked") public List<GenSolvablePolynomial> nextSolvablePolynomialList() throws IOException { List<GenPolynomial> s = nextPolynomialList(); logger.info("s = " + s); // comments += nextComment(); GenPolynomial p; GenSolvablePolynomial ps; List<GenSolvablePolynomial> sp = new ArrayList<GenSolvablePolynomial>(s.size()); for (Iterator<GenPolynomial> it = s.iterator(); it.hasNext();) { p = it.next(); ps = new GenSolvablePolynomial(spfac, p.val); //System.out.println("ps = " + ps); sp.add(ps); } return sp; } /** * Parsing method for solvable polynomial. syntax: p. * @return the next polynomial. * @throws IOException */ @SuppressWarnings("unchecked") public GenSolvablePolynomial nextSolvablePolynomial() throws IOException { GenPolynomial p = nextPolynomial(); logger.info("p = " + p); // comments += nextComment(); GenSolvablePolynomial ps = new GenSolvablePolynomial(spfac, p.val); //System.out.println("ps = " + ps); return ps; } /** * Parsing method for solvable polynomial set. syntax: varList termOrderName * relationTable polyList. * @return the next solvable polynomial set. * @throws IOException */ @SuppressWarnings("unchecked") public PolynomialList nextSolvablePolynomialSet() throws IOException { //String comments = ""; //comments += nextComment(); //if (debug) logger.debug("comment = " + comments); RingFactory coeff = nextCoefficientRing(); logger.info("coeff = " + coeff); vars = nextVariableList(); String dd = "vars ="; for (int i = 0; i < vars.length; i++) { dd += " " + vars[i]; } logger.info(dd); if (vars != null) { nvars = vars.length; } tord = nextTermOrder(); logger.info("tord = " + tord); // check more TOs initFactory(coeff, parsedCoeff); // must be because of symmetric read initSolvableFactory(coeff, parsedCoeff); // global: nvars, tord, vars //System.out.println("pfac = " + pfac); //System.out.println("spfac = " + spfac); nextRelationTable(); if (logger.isInfoEnabled()) { logger.info("table = " + table); } List<GenSolvablePolynomial> s = null; s = nextSolvablePolynomialList(); logger.info("s = " + s); // comments += nextComment(); return new PolynomialList(spfac, s); // Ordered ? } /** * Parsing method for solvable submodule list. syntax: ( ( p11, p12, p13, * ..., p1n ), ..., ( pm1, pm2, pm3, ..., pmn ) ) * @return the next list of solvable polynomial lists. * @throws IOException */ public List<List<GenSolvablePolynomial>> nextSolvableSubModuleList() throws IOException { List<List<GenSolvablePolynomial>> L = new ArrayList<List<GenSolvablePolynomial>>(); int tt; tt = tok.nextToken(); if (tt == StreamTokenizer.TT_EOF) return L; if (tt != '(') return L; logger.debug("module list"); List<GenSolvablePolynomial> v = null; while (true) { tt = tok.nextToken(); if (tok.ttype == ',') continue; if (tok.ttype == ')') break; if (tok.ttype == StreamTokenizer.TT_EOF) break; if (tt == '(') { tok.pushBack(); v = nextSolvablePolynomialList(); logger.info("next vect = " + v); L.add(v); } } return L; } /** * Parsing method for solvable module set. syntax: varList termOrderName * relationTable moduleList. * @return the next solvable module set. * @throws IOException */ @SuppressWarnings("unchecked") public ModuleList nextSolvableSubModuleSet() throws IOException { //String comments = ""; //comments += nextComment(); //if (debug) logger.debug("comment = " + comments); RingFactory coeff = nextCoefficientRing(); logger.info("coeff = " + coeff); vars = nextVariableList(); String dd = "vars ="; for (int i = 0; i < vars.length; i++) { dd += " " + vars[i]; } logger.info(dd); if (vars != null) { nvars = vars.length; } tord = nextTermOrder(); logger.info("tord = " + tord); // check more TOs initFactory(coeff, parsedCoeff); // must be because of symmetric read initSolvableFactory(coeff, parsedCoeff); // global: nvars, tord, vars //System.out.println("spfac = " + spfac); nextRelationTable(); if (logger.isInfoEnabled()) { logger.info("table = " + table); } List<List<GenSolvablePolynomial>> s = null; s = nextSolvableSubModuleList(); logger.info("s = " + s); // comments += nextComment(); return new OrderedModuleList(spfac, s); // Ordered } // must also allow +/- // does not work with tokenizer private static boolean number(char x) { return digit(x) || x == '-' || x == '+'; } private static boolean digit(char x) { return '0' <= x && x <= '9'; } private static boolean letter(char x) { return ('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z'); } // unused public void nextComma() throws IOException { int tt; if (tok.ttype == ',') { if (debug) logger.debug("comma: "); tt = tok.nextToken(); } } /** * Parse variable list from String. * @param s String. Syntax: (n1,...,nk) or (n1 ... nk), parenthesis are also * optional. * @return array of variable names found in s. */ public static String[] variableList(String s) { String[] vl = null; if (s == null) { return vl; } String st = s.trim(); if (st.length() == 0) { return new String[0]; } if (st.charAt(0) == '(') { st = st.substring(1); } if (st.charAt(st.length() - 1) == ')') { st = st.substring(0, st.length() - 1); } st = st.replaceAll(",", " "); List<String> sl = new ArrayList<String>(); Scanner sc = new Scanner(st); while (sc.hasNext()) { String sn = sc.next(); sl.add(sn); } vl = new String[sl.size()]; int i = 0; for (String si : sl) { vl[i] = si; i++; } return vl; } /** * Extract variable list from expression. * @param s String. Syntax: any polynomial expression. * @return array of variable names found in s. */ public static String[] expressionVariables(String s) { String[] vl = null; if (s == null) { return vl; } String st = s.trim(); if (st.length() == 0) { return new String[0]; } st = st.replaceAll(",", " "); st = st.replaceAll("\\+", " "); st = st.replaceAll("-", " "); st = st.replaceAll("\\*", " "); st = st.replaceAll("/", " "); st = st.replaceAll("\\(", " "); st = st.replaceAll("\\)", " "); st = st.replaceAll("\\{", " "); st = st.replaceAll("\\}", " "); st = st.replaceAll("\\[", " "); st = st.replaceAll("\\]", " "); st = st.replaceAll("\\^", " "); //System.out.println("st = " + st); Set<String> sl = new TreeSet<String>(); Scanner sc = new Scanner(st); while (sc.hasNext()) { String sn = sc.next(); if ( sn == null || sn.length() == 0 ) { continue; } //System.out.println("sn = " + sn); int i = 0; while ( digit(sn.charAt(i)) && i < sn.length()-1 ) { i++; } //System.out.println("sn = " + sn + ", i = " + i); if ( i > 0 ) { sn = sn.substring(i,sn.length()); } //System.out.println("sn = " + sn); if ( sn.length() == 0 ) { continue; } if ( ! letter(sn.charAt(0)) ) { continue; } //System.out.println("sn = " + sn); sl.add(sn); } vl = new String[sl.size()]; int i = 0; for (String si : sl) { vl[i] = si; i++; } return vl; } }
false
true
public GenPolynomial nextPolynomial() throws IOException { if (debug) { logger.debug("torder = " + tord); } GenPolynomial a = pfac.getZERO(); GenPolynomial a1 = pfac.getONE(); ExpVector leer = pfac.evzero; if (debug) { logger.debug("a = " + a); logger.debug("a1 = " + a1); } GenPolynomial b = a1; GenPolynomial c; int tt; //, oldtt; //String rat = ""; char first; RingElem r; ExpVector e; int ix; long ie; boolean done = false; while (!done) { // next input. determine next action tt = tok.nextToken(); //System.out.println("while tt = " + tok); logger.debug("while tt = " + tok); if (tt == StreamTokenizer.TT_EOF) break; switch (tt) { case ')': case ',': return a; // do not change or remove case '-': b = b.negate(); case '+': case '*': tt = tok.nextToken(); break; default: // skip } // read coefficient, monic monomial and polynomial if (tt == StreamTokenizer.TT_EOF) break; switch (tt) { // case '_': removed case '}': throw new InvalidExpressionException("mismatch of braces after " + a + ", error at " + b); case '{': // recursion StringBuffer rf = new StringBuffer(); int level = 0; do { tt = tok.nextToken(); //System.out.println("token { = " + ((char)tt) + ", " + tt + ", level = " + level); if (tt == StreamTokenizer.TT_EOF) { throw new InvalidExpressionException("mismatch of braces after " + a + ", error at " + b); } if (tt == '{') { level++; } if (tt == '}') { level--; if (level < 0) { continue; // skip last closing brace } } if (tok.sval != null) { if (rf.length() > 0 && rf.charAt(rf.length() - 1) != '.') { rf.append(" "); } rf.append(tok.sval); // " " + } else { rf.append((char) tt); } } while (level >= 0); //System.out.println("coeff{} = " + rf.toString() ); try { r = (RingElem) fac.parse(rf.toString()); } catch (NumberFormatException re) { throw new InvalidExpressionException("not a number " + rf, re); } if (debug) logger.debug("coeff " + r); ie = nextExponent(); if (debug) logger.debug("ie " + ie); r = Power.<RingElem> positivePower(r, ie); if (debug) logger.debug("coeff^ie " + r); b = b.multiply(r, leer); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); //no break; break; case StreamTokenizer.TT_WORD: //System.out.println("TT_WORD: " + tok.sval); if (tok.sval == null || tok.sval.length() == 0) break; // read coefficient first = tok.sval.charAt(0); if (digit(first)) { //System.out.println("coeff 0 = " + tok.sval ); StringBuffer df = new StringBuffer(); df.append(tok.sval); tt = tok.nextToken(); if (tt == '.') { tt = tok.nextToken(); if (debug) logger.debug("tt,dot = " + tok); if (tok.sval != null) { df.append("."); df.append(tok.sval); } else { tok.pushBack(); tok.pushBack(); } } else { tok.pushBack(); } try { r = (RingElem) fac.parse(df.toString()); } catch (NumberFormatException re) { throw new InvalidExpressionException("not a number " + df, re); } if (debug) logger.debug("coeff " + r); //System.out.println("r = " + r.toScriptFactory()); ie = nextExponent(); if (debug) logger.debug("ie " + ie); // r = r^ie; r = Power.<RingElem> positivePower(r, ie); if (debug) logger.debug("coeff^ie " + r); b = b.multiply(r, leer); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); } if (tt == StreamTokenizer.TT_EOF) break; if (tok.sval == null) break; // read monomial or recursion first = tok.sval.charAt(0); if (letter(first)) { ix = leer.indexVar(tok.sval, vars); //indexVar( tok.sval ); if (ix < 0) { // not found try { r = (RingElem) fac.parse(tok.sval); } catch (NumberFormatException re) { throw new InvalidExpressionException("recursively unknown variable " + tok.sval); } if (debug) logger.info("coeff " + r); if (r.isONE() || r.isZERO()) { //logger.error("Unknown varibable " + tok.sval); //done = true; //break; throw new InvalidExpressionException("recursively unknown variable " + tok.sval); } ie = nextExponent(); // System.out.println("ie: " + ie); r = Power.<RingElem> positivePower(r, ie); b = b.multiply(r); } else { // found // System.out.println("ix: " + ix); ie = nextExponent(); // System.out.println("ie: " + ie); e = ExpVector.create(vars.length, ix, ie); b = b.multiply(e); } tt = tok.nextToken(); if (debug) logger.debug("tt,letter = " + tok); } break; case '(': c = nextPolynomial(); if (debug) logger.debug("factor " + c); ie = nextExponent(); if (debug) logger.debug("ie " + ie); c = Power.<GenPolynomial> positivePower(c, ie); if (debug) logger.debug("factor^ie " + c); b = b.multiply(c); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); //no break; break; default: //skip } if (done) break; // unknown variable if (tt == StreamTokenizer.TT_EOF) break; // complete polynomial tok.pushBack(); switch (tt) { case '-': case '+': case ')': case ',': logger.debug("b, = " + b); a = a.sum(b); b = a1; break; case '*': logger.debug("b, = " + b); //a = a.sum(b); //b = a1; break; case '\n': tt = tok.nextToken(); if (debug) logger.debug("tt,nl = " + tt); default: // skip or finish ? if (debug) logger.debug("default: " + tok); } } if (debug) logger.debug("b = " + b); a = a.sum(b); logger.debug("a = " + a); // b = a1; return a; }
public GenPolynomial nextPolynomial() throws IOException { if (debug) { logger.debug("torder = " + tord); } GenPolynomial a = pfac.getZERO(); GenPolynomial a1 = pfac.getONE(); ExpVector leer = pfac.evzero; if (debug) { logger.debug("a = " + a); logger.debug("a1 = " + a1); } GenPolynomial b = a1; GenPolynomial c; int tt; //, oldtt; //String rat = ""; char first; RingElem r; ExpVector e; int ix; long ie; boolean done = false; while (!done) { // next input. determine next action tt = tok.nextToken(); //System.out.println("while tt = " + tok); logger.debug("while tt = " + tok); if (tt == StreamTokenizer.TT_EOF) break; switch (tt) { case ')': case ',': return a; // do not change or remove case '-': b = b.negate(); case '+': case '*': tt = tok.nextToken(); break; default: // skip } // read coefficient, monic monomial and polynomial if (tt == StreamTokenizer.TT_EOF) break; switch (tt) { // case '_': removed case '}': throw new InvalidExpressionException("mismatch of braces after " + a + ", error at " + b); case '{': // recursion StringBuffer rf = new StringBuffer(); int level = 0; do { tt = tok.nextToken(); //System.out.println("token { = " + ((char)tt) + ", " + tt + ", level = " + level); if (tt == StreamTokenizer.TT_EOF) { throw new InvalidExpressionException("mismatch of braces after " + a + ", error at " + b); } if (tt == '{') { level++; } if (tt == '}') { level--; if (level < 0) { continue; // skip last closing brace } } if (tok.sval != null) { if (rf.length() > 0 && rf.charAt(rf.length() - 1) != '.') { rf.append(" "); } rf.append(tok.sval); // " " + } else { rf.append((char) tt); } } while (level >= 0); //System.out.println("coeff{} = " + rf.toString() ); try { r = (RingElem) fac.parse(rf.toString()); } catch (NumberFormatException re) { throw new InvalidExpressionException("not a number " + rf, re); } if (debug) logger.debug("coeff " + r); ie = nextExponent(); if (debug) logger.debug("ie " + ie); r = Power.<RingElem> positivePower(r, ie); if (debug) logger.debug("coeff^ie " + r); b = b.multiply(r, leer); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); //no break; break; case StreamTokenizer.TT_WORD: //System.out.println("TT_WORD: " + tok.sval); if (tok.sval == null || tok.sval.length() == 0) break; // read coefficient first = tok.sval.charAt(0); if (digit(first)) { //System.out.println("coeff 0 = " + tok.sval ); StringBuffer df = new StringBuffer(); df.append(tok.sval); tt = tok.nextToken(); if (tt == '.') { tt = tok.nextToken(); if (debug) logger.debug("tt,dot = " + tok); if (tok.sval != null) { df.append("."); df.append(tok.sval); } else { tok.pushBack(); tok.pushBack(); } } else { tok.pushBack(); } try { r = (RingElem) fac.parse(df.toString()); } catch (NumberFormatException re) { throw new InvalidExpressionException("not a number " + df, re); } if (debug) logger.debug("coeff " + r); //System.out.println("r = " + r.toScriptFactory()); ie = nextExponent(); if (debug) logger.debug("ie " + ie); // r = r^ie; r = Power.<RingElem> positivePower(r, ie); if (debug) logger.debug("coeff^ie " + r); b = b.multiply(r, leer); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); } if (tt == StreamTokenizer.TT_EOF) break; if (tok.sval == null) break; // read monomial or recursion first = tok.sval.charAt(0); if (letter(first)) { ix = leer.indexVar(tok.sval, vars); //indexVar( tok.sval ); if (ix < 0) { // not found try { r = (RingElem) fac.parse(tok.sval); } catch (NumberFormatException re) { throw new InvalidExpressionException("recursively unknown variable " + tok.sval); } if (debug) logger.info("coeff " + r); //if (r.isONE() || r.isZERO()) { //logger.error("Unknown varibable " + tok.sval); //done = true; //break; //throw new InvalidExpressionException("recursively unknown variable " + tok.sval); //} ie = nextExponent(); // System.out.println("ie: " + ie); r = Power.<RingElem> positivePower(r, ie); b = b.multiply(r); } else { // found // System.out.println("ix: " + ix); ie = nextExponent(); // System.out.println("ie: " + ie); e = ExpVector.create(vars.length, ix, ie); b = b.multiply(e); } tt = tok.nextToken(); if (debug) logger.debug("tt,letter = " + tok); } break; case '(': c = nextPolynomial(); if (debug) logger.debug("factor " + c); ie = nextExponent(); if (debug) logger.debug("ie " + ie); c = Power.<GenPolynomial> positivePower(c, ie); if (debug) logger.debug("factor^ie " + c); b = b.multiply(c); tt = tok.nextToken(); if (debug) logger.debug("tt,digit = " + tok); //no break; break; default: //skip } if (done) break; // unknown variable if (tt == StreamTokenizer.TT_EOF) break; // complete polynomial tok.pushBack(); switch (tt) { case '-': case '+': case ')': case ',': logger.debug("b, = " + b); a = a.sum(b); b = a1; break; case '*': logger.debug("b, = " + b); //a = a.sum(b); //b = a1; break; case '\n': tt = tok.nextToken(); if (debug) logger.debug("tt,nl = " + tt); default: // skip or finish ? if (debug) logger.debug("default: " + tok); } } if (debug) logger.debug("b = " + b); a = a.sum(b); logger.debug("a = " + a); // b = a1; return a; }
diff --git a/services/src/main/java/edu/unc/lib/dl/cdr/services/techmd/TechnicalMetadataEnhancement.java b/services/src/main/java/edu/unc/lib/dl/cdr/services/techmd/TechnicalMetadataEnhancement.java index 024a4c159..c550bf03a 100644 --- a/services/src/main/java/edu/unc/lib/dl/cdr/services/techmd/TechnicalMetadataEnhancement.java +++ b/services/src/main/java/edu/unc/lib/dl/cdr/services/techmd/TechnicalMetadataEnhancement.java @@ -1,375 +1,377 @@ /** * Copyright 2008 The University of North Carolina at Chapel Hill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.unc.lib.dl.cdr.services.techmd; import static edu.unc.lib.dl.xml.JDOMNamespaceUtil.FITS_NS; import static edu.unc.lib.dl.xml.JDOMNamespaceUtil.PREMIS_V2_NS; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.util.URIUtil; import org.apache.commons.lang.exception.ExceptionUtils; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.unc.lib.dl.cdr.services.Enhancement; import edu.unc.lib.dl.cdr.services.JMSMessageUtil; import edu.unc.lib.dl.cdr.services.exception.EnhancementException; import edu.unc.lib.dl.cdr.services.exception.EnhancementException.Severity; import edu.unc.lib.dl.cdr.services.model.PIDMessage; import edu.unc.lib.dl.fedora.FedoraException; import edu.unc.lib.dl.fedora.FileSystemException; import edu.unc.lib.dl.fedora.NotFoundException; import edu.unc.lib.dl.fedora.PID; import edu.unc.lib.dl.fedora.types.Datastream; import edu.unc.lib.dl.util.ContentModelHelper; import edu.unc.lib.dl.xml.FOXMLJDOMUtil; import edu.unc.lib.dl.xml.JDOMNamespaceUtil; /** * Executes irods script which uses FITS to extract technical metadata features of objects with data file datastreams. * * @author Gregory Jansen * */ public class TechnicalMetadataEnhancement extends Enhancement<Element> { Namespace ns = JDOMNamespaceUtil.FITS_NS; private static final Logger LOG = LoggerFactory.getLogger(TechnicalMetadataEnhancement.class); private TechnicalMetadataEnhancementService service = null; /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public Element call() throws EnhancementException { Element result = null; // check to see if the service is still active if (!this.service.isActive()) { LOG.debug(this.getClass().getName() + " call method exited, service is not active."); return null; } // get sourceData data stream IDs List<String> srcDSURIs = this.service.getTripleStoreQueryService().getSourceData(pid.getPID()); Map<String, Document> ds2FitsDoc = new HashMap<String, Document>(); try { Document foxml = service.getManagementClient().getObjectXML(pid.getPID()); for (String srcURI : srcDSURIs) { // for each source datastream LOG.debug("source data URI: " + srcURI); String dsid = srcURI.substring(srcURI.lastIndexOf("/") + 1); LOG.debug("datastream ID: " + dsid); // get current datastream version ID String dsLocation = null; String dsIrodsPath = null; String dsAltIds = null; Datastream ds = service.getManagementClient().getDatastream(pid.getPID(), dsid, ""); String vid = ds.getVersionID(); Element dsEl = FOXMLJDOMUtil.getDatastream(foxml, dsid); for (Object o : dsEl.getChildren("datastreamVersion", JDOMNamespaceUtil.FOXML_NS)) { if (o instanceof Element) { Element dsvEl = (Element) o; if (vid.equals(dsvEl.getAttributeValue("ID"))) { dsLocation = dsvEl.getChild("contentLocation", JDOMNamespaceUtil.FOXML_NS) .getAttributeValue("REF"); dsAltIds = dsvEl.getAttributeValue("ALT_IDS"); break; } } } // get logical iRODS path for datastream version dsIrodsPath = service.getManagementClient().getIrodsPath(dsLocation); // call fits via irods rule for the locations Document fits = null; try { fits = runFITS(dsIrodsPath, dsAltIds); + } catch (JDOMException e){ + LOG.warn("Failed to parse FITS response", e); + return null; } catch (Exception e) { - LOG.error("Run Fits failed", e); - throw new EnhancementException(e); + throw new EnhancementException(e, Severity.UNRECOVERABLE); } // put the FITS document in DS map ds2FitsDoc.put(dsid, fits); } // build a PREMIS document Document premisTech = new Document(); Element p = new Element("premis", PREMIS_V2_NS); premisTech.addContent(p); for (String dsid : ds2FitsDoc.keySet()) { // get key PREMIS data Document fits = ds2FitsDoc.get(dsid); String md5checksum = fits.getRootElement().getChild("fileinfo", FITS_NS) .getChildText("md5checksum", FITS_NS); String size = fits.getRootElement().getChild("fileinfo", FITS_NS).getChildText("size", FITS_NS); // IDENTIFICATION LOGIC // get mimetype out of FITS XML Element trustedIdentity = null; Element idn = fits.getRootElement().getChild("identification", ns); for (Object child : idn.getChildren("identity", ns)) { Element el = (Element) child; if (idn.getAttributeValue("status") == null || el.getChildren("tool", ns).size() > 1 || (!"Exiftool".equals(el.getChild("tool", ns).getAttributeValue("toolname")) && !"application/x-symlink" .equals(el.getAttributeValue("mimetype")))) { trustedIdentity = el; break; } } String fitsMimetype = null; String format = null; if (trustedIdentity != null) { fitsMimetype = trustedIdentity.getAttributeValue("mimetype"); format = trustedIdentity.getAttributeValue("format"); } else { format = "Unknown"; LOG.warn("FITS unable to conclusively identify file: " + pid.getPID() + "/" + dsid); LOG.warn(new XMLOutputter().outputString(fits)); } if ("DATA_FILE".equals(dsid)) { if (fitsMimetype != null) { setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceMimeType.toString(), fitsMimetype, null); } else { // application/octet-stream setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceMimeType.toString(), "application/octet-stream", null); } try { Long.parseLong(size); setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceFileSize.toString(), size, "http://www.w3.org/2001/XMLSchema#long"); } catch (NumberFormatException e) { LOG.error("FITS produced a non-integer value for size: " + size); } } p.addContent(new Element("object", PREMIS_V2_NS) .addContent( new Element("objectIdentifier", PREMIS_V2_NS).addContent( new Element("objectIdentifierType", PREMIS_V2_NS).setText("Fedora Datastream PID")) .addContent(new Element("objectIdentifierValue", PREMIS_V2_NS).setText(dsid))) .addContent( new Element("objectCharacteristics", PREMIS_V2_NS) .addContent(new Element("compositionLevel", PREMIS_V2_NS).setText("0")) .addContent( new Element("fixity", PREMIS_V2_NS).addContent( new Element("messageDigestAlgorithm", PREMIS_V2_NS).setText("MD5")) .addContent(new Element("messageDigest", PREMIS_V2_NS).setText(md5checksum))) .addContent(new Element("size", PREMIS_V2_NS).setText(size)) .addContent( new Element("format", PREMIS_V2_NS).addContent(new Element("formatDesignation", PREMIS_V2_NS).addContent(new Element("formatName", PREMIS_V2_NS) .setText(format)))) .addContent( new Element("objectCharacteristicsExtension", PREMIS_V2_NS).addContent(ds2FitsDoc .get(dsid).detachRootElement()))) .setAttribute("type", PREMIS_V2_NS.getPrefix() + ":file", JDOMNamespaceUtil.XSI_NS)); } // upload tech MD PREMIS XML String premisTechURL = service.getManagementClient().upload(premisTech); // Add or replace the MD_TECHNICAL datastream for the object if (FOXMLJDOMUtil.getDatastream(foxml, ContentModelHelper.Datastream.MD_TECHNICAL.getName()) == null) { LOG.debug("Adding FITS output to MD_TECHNICAL"); //Ignore the add DS message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.ADD_DATASTREAM.toString(), null, ContentModelHelper.Datastream.MD_TECHNICAL.toString()); String message = "Adding technical metadata derived by FITS"; String newDSID = service.getManagementClient().addManagedDatastream(pid.getPID(), ContentModelHelper.Datastream.MD_TECHNICAL.getName(), false, message, new ArrayList<String>(), "PREMIS Technical Metadata", false, "text/xml", premisTechURL); } else { LOG.debug("Replacing MD_TECHNICAL with new FITS output"); //Ignore modify DS message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.MODIFY_DATASTREAM_BY_REFERENCE.toString(), null, ContentModelHelper.Datastream.MD_TECHNICAL.toString()); String message = "Replacing technical metadata derived by FITS"; service.getManagementClient().modifyDatastreamByReference(pid.getPID(), ContentModelHelper.Datastream.MD_TECHNICAL.getName(), false, message, new ArrayList<String>(), "PREMIS Technical Metadata", "text/xml", null, null, premisTechURL); } LOG.debug("Adding techData relationship"); PID newDSPID = new PID(pid.getPID().getPid() + "/" + ContentModelHelper.Datastream.MD_TECHNICAL.getName()); Map<String, List<String>> rels = service.getTripleStoreQueryService().fetchAllTriples(pid.getPID()); List<String> techrel = rels.get(ContentModelHelper.CDRProperty.techData.toString()); if (techrel == null || !techrel.contains(newDSPID.getURI())) { //Ignore the add relation message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.ADD_RELATIONSHIP.toString(), null, ContentModelHelper.CDRProperty.techData.toString()); service.getManagementClient().addObjectRelationship(pid.getPID(), ContentModelHelper.CDRProperty.techData.toString(), newDSPID); } LOG.debug("Finished MD_TECHNICAL updating for " + pid.getPID()); } catch (FileSystemException e) { throw new EnhancementException(e, Severity.FATAL); } catch (NotFoundException e) { throw new EnhancementException(e, Severity.UNRECOVERABLE); } catch (FedoraException e) { throw new EnhancementException(e, Severity.RECOVERABLE); } return result; } /** * Set a single value for a given predicate and pid. * * @param pid * @param predicate * @param newExclusiveValue * @throws FedoraException */ private void setExclusiveTripleValue(PID pid, String predicate, String newExclusiveValue, String datatype) throws FedoraException { List<String> rel = service.getTripleStoreQueryService().fetchAllTriples(pid).get(predicate); if (rel != null) { if (rel.contains(newExclusiveValue)) { rel.remove(newExclusiveValue); } else { //Ignore the add relation message service.getServicesConductor().addSideEffect(pid.getPid(), JMSMessageUtil.FedoraActions.ADD_RELATIONSHIP.toString(), null, predicate); // add missing rel service.getManagementClient().addLiteralStatement(pid, predicate, newExclusiveValue, datatype); } // remove any other same predicate triples for (String oldValue : rel) { service.getServicesConductor().addSideEffect(pid.getPid(), JMSMessageUtil.FedoraActions.PURGE_RELATIONSHIP.toString(), null, predicate); service.getManagementClient().purgeLiteralStatement(pid, predicate, oldValue, datatype); } } else { service.getServicesConductor().addSideEffect(pid.getPid(), JMSMessageUtil.FedoraActions.ADD_RELATIONSHIP.toString(), null, predicate); // add missing rel service.getManagementClient().addLiteralStatement(pid, predicate, newExclusiveValue, datatype); } } /** * Executes fits extract irods script * * @param dsIrodsPath * @return FITS output XML Document */ private Document runFITS(String dsIrodsPath, String altIds) throws Exception { Document result = null; // try to extract file name from ALT_ID String filename = null; if (altIds != null) { for (String altid : altIds.split(" ")) { if (altid.length() > 0) { URI alt = new URI(altid); int ind = alt.getRawPath().lastIndexOf("."); if (ind > 0 && alt.getRawPath().length() - 1 > ind) { filename = alt.getRawPath().substring(ind + 1); filename = URIUtil.decode("linkedfile."+filename); break; } } } } // execute FITS LOG.debug("Run fits for " + dsIrodsPath); BufferedReader reader = null; String xmlstr = null; String errstr = null; try { if (filename == null) { reader = new BufferedReader(new InputStreamReader(service.remoteExecuteWithPhysicalLocation("fitsextract", dsIrodsPath))); } else { reader = new BufferedReader(new InputStreamReader(service.remoteExecuteWithPhysicalLocation("fitsextract", "'" + filename + "'", dsIrodsPath))); } StringBuilder xml = new StringBuilder(); StringBuilder err = new StringBuilder(); boolean blankReached = false; for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (line.trim().length() == 0) { blankReached = true; continue; } else { if (blankReached) { err.append(line).append("\n"); } else { xml.append(line).append("\n"); } } } xmlstr = xml.toString(); errstr = err.toString(); if (errstr.length() > 0) { LOG.warn("FITS is warning for path: " + dsIrodsPath + "\n" + errstr); } result = new SAXBuilder().build(new StringReader(xmlstr)); return result; } catch(JDOMException e) { LOG.warn("Failed to parse FITS output: "+e.getMessage()); LOG.warn("FITS returned: \n"+xmlstr+"\n\n"+errstr); throw e; } finally { if (reader != null) { reader.close(); } } } public TechnicalMetadataEnhancement(TechnicalMetadataEnhancementService technicalMetadataEnhancementService, PIDMessage pid) { super(pid); this.service = technicalMetadataEnhancementService; } }
false
true
public Element call() throws EnhancementException { Element result = null; // check to see if the service is still active if (!this.service.isActive()) { LOG.debug(this.getClass().getName() + " call method exited, service is not active."); return null; } // get sourceData data stream IDs List<String> srcDSURIs = this.service.getTripleStoreQueryService().getSourceData(pid.getPID()); Map<String, Document> ds2FitsDoc = new HashMap<String, Document>(); try { Document foxml = service.getManagementClient().getObjectXML(pid.getPID()); for (String srcURI : srcDSURIs) { // for each source datastream LOG.debug("source data URI: " + srcURI); String dsid = srcURI.substring(srcURI.lastIndexOf("/") + 1); LOG.debug("datastream ID: " + dsid); // get current datastream version ID String dsLocation = null; String dsIrodsPath = null; String dsAltIds = null; Datastream ds = service.getManagementClient().getDatastream(pid.getPID(), dsid, ""); String vid = ds.getVersionID(); Element dsEl = FOXMLJDOMUtil.getDatastream(foxml, dsid); for (Object o : dsEl.getChildren("datastreamVersion", JDOMNamespaceUtil.FOXML_NS)) { if (o instanceof Element) { Element dsvEl = (Element) o; if (vid.equals(dsvEl.getAttributeValue("ID"))) { dsLocation = dsvEl.getChild("contentLocation", JDOMNamespaceUtil.FOXML_NS) .getAttributeValue("REF"); dsAltIds = dsvEl.getAttributeValue("ALT_IDS"); break; } } } // get logical iRODS path for datastream version dsIrodsPath = service.getManagementClient().getIrodsPath(dsLocation); // call fits via irods rule for the locations Document fits = null; try { fits = runFITS(dsIrodsPath, dsAltIds); } catch (Exception e) { LOG.error("Run Fits failed", e); throw new EnhancementException(e); } // put the FITS document in DS map ds2FitsDoc.put(dsid, fits); } // build a PREMIS document Document premisTech = new Document(); Element p = new Element("premis", PREMIS_V2_NS); premisTech.addContent(p); for (String dsid : ds2FitsDoc.keySet()) { // get key PREMIS data Document fits = ds2FitsDoc.get(dsid); String md5checksum = fits.getRootElement().getChild("fileinfo", FITS_NS) .getChildText("md5checksum", FITS_NS); String size = fits.getRootElement().getChild("fileinfo", FITS_NS).getChildText("size", FITS_NS); // IDENTIFICATION LOGIC // get mimetype out of FITS XML Element trustedIdentity = null; Element idn = fits.getRootElement().getChild("identification", ns); for (Object child : idn.getChildren("identity", ns)) { Element el = (Element) child; if (idn.getAttributeValue("status") == null || el.getChildren("tool", ns).size() > 1 || (!"Exiftool".equals(el.getChild("tool", ns).getAttributeValue("toolname")) && !"application/x-symlink" .equals(el.getAttributeValue("mimetype")))) { trustedIdentity = el; break; } } String fitsMimetype = null; String format = null; if (trustedIdentity != null) { fitsMimetype = trustedIdentity.getAttributeValue("mimetype"); format = trustedIdentity.getAttributeValue("format"); } else { format = "Unknown"; LOG.warn("FITS unable to conclusively identify file: " + pid.getPID() + "/" + dsid); LOG.warn(new XMLOutputter().outputString(fits)); } if ("DATA_FILE".equals(dsid)) { if (fitsMimetype != null) { setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceMimeType.toString(), fitsMimetype, null); } else { // application/octet-stream setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceMimeType.toString(), "application/octet-stream", null); } try { Long.parseLong(size); setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceFileSize.toString(), size, "http://www.w3.org/2001/XMLSchema#long"); } catch (NumberFormatException e) { LOG.error("FITS produced a non-integer value for size: " + size); } } p.addContent(new Element("object", PREMIS_V2_NS) .addContent( new Element("objectIdentifier", PREMIS_V2_NS).addContent( new Element("objectIdentifierType", PREMIS_V2_NS).setText("Fedora Datastream PID")) .addContent(new Element("objectIdentifierValue", PREMIS_V2_NS).setText(dsid))) .addContent( new Element("objectCharacteristics", PREMIS_V2_NS) .addContent(new Element("compositionLevel", PREMIS_V2_NS).setText("0")) .addContent( new Element("fixity", PREMIS_V2_NS).addContent( new Element("messageDigestAlgorithm", PREMIS_V2_NS).setText("MD5")) .addContent(new Element("messageDigest", PREMIS_V2_NS).setText(md5checksum))) .addContent(new Element("size", PREMIS_V2_NS).setText(size)) .addContent( new Element("format", PREMIS_V2_NS).addContent(new Element("formatDesignation", PREMIS_V2_NS).addContent(new Element("formatName", PREMIS_V2_NS) .setText(format)))) .addContent( new Element("objectCharacteristicsExtension", PREMIS_V2_NS).addContent(ds2FitsDoc .get(dsid).detachRootElement()))) .setAttribute("type", PREMIS_V2_NS.getPrefix() + ":file", JDOMNamespaceUtil.XSI_NS)); } // upload tech MD PREMIS XML String premisTechURL = service.getManagementClient().upload(premisTech); // Add or replace the MD_TECHNICAL datastream for the object if (FOXMLJDOMUtil.getDatastream(foxml, ContentModelHelper.Datastream.MD_TECHNICAL.getName()) == null) { LOG.debug("Adding FITS output to MD_TECHNICAL"); //Ignore the add DS message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.ADD_DATASTREAM.toString(), null, ContentModelHelper.Datastream.MD_TECHNICAL.toString()); String message = "Adding technical metadata derived by FITS"; String newDSID = service.getManagementClient().addManagedDatastream(pid.getPID(), ContentModelHelper.Datastream.MD_TECHNICAL.getName(), false, message, new ArrayList<String>(), "PREMIS Technical Metadata", false, "text/xml", premisTechURL); } else { LOG.debug("Replacing MD_TECHNICAL with new FITS output"); //Ignore modify DS message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.MODIFY_DATASTREAM_BY_REFERENCE.toString(), null, ContentModelHelper.Datastream.MD_TECHNICAL.toString()); String message = "Replacing technical metadata derived by FITS"; service.getManagementClient().modifyDatastreamByReference(pid.getPID(), ContentModelHelper.Datastream.MD_TECHNICAL.getName(), false, message, new ArrayList<String>(), "PREMIS Technical Metadata", "text/xml", null, null, premisTechURL); } LOG.debug("Adding techData relationship"); PID newDSPID = new PID(pid.getPID().getPid() + "/" + ContentModelHelper.Datastream.MD_TECHNICAL.getName()); Map<String, List<String>> rels = service.getTripleStoreQueryService().fetchAllTriples(pid.getPID()); List<String> techrel = rels.get(ContentModelHelper.CDRProperty.techData.toString()); if (techrel == null || !techrel.contains(newDSPID.getURI())) { //Ignore the add relation message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.ADD_RELATIONSHIP.toString(), null, ContentModelHelper.CDRProperty.techData.toString()); service.getManagementClient().addObjectRelationship(pid.getPID(), ContentModelHelper.CDRProperty.techData.toString(), newDSPID); } LOG.debug("Finished MD_TECHNICAL updating for " + pid.getPID()); } catch (FileSystemException e) { throw new EnhancementException(e, Severity.FATAL); } catch (NotFoundException e) { throw new EnhancementException(e, Severity.UNRECOVERABLE); } catch (FedoraException e) { throw new EnhancementException(e, Severity.RECOVERABLE); } return result; }
public Element call() throws EnhancementException { Element result = null; // check to see if the service is still active if (!this.service.isActive()) { LOG.debug(this.getClass().getName() + " call method exited, service is not active."); return null; } // get sourceData data stream IDs List<String> srcDSURIs = this.service.getTripleStoreQueryService().getSourceData(pid.getPID()); Map<String, Document> ds2FitsDoc = new HashMap<String, Document>(); try { Document foxml = service.getManagementClient().getObjectXML(pid.getPID()); for (String srcURI : srcDSURIs) { // for each source datastream LOG.debug("source data URI: " + srcURI); String dsid = srcURI.substring(srcURI.lastIndexOf("/") + 1); LOG.debug("datastream ID: " + dsid); // get current datastream version ID String dsLocation = null; String dsIrodsPath = null; String dsAltIds = null; Datastream ds = service.getManagementClient().getDatastream(pid.getPID(), dsid, ""); String vid = ds.getVersionID(); Element dsEl = FOXMLJDOMUtil.getDatastream(foxml, dsid); for (Object o : dsEl.getChildren("datastreamVersion", JDOMNamespaceUtil.FOXML_NS)) { if (o instanceof Element) { Element dsvEl = (Element) o; if (vid.equals(dsvEl.getAttributeValue("ID"))) { dsLocation = dsvEl.getChild("contentLocation", JDOMNamespaceUtil.FOXML_NS) .getAttributeValue("REF"); dsAltIds = dsvEl.getAttributeValue("ALT_IDS"); break; } } } // get logical iRODS path for datastream version dsIrodsPath = service.getManagementClient().getIrodsPath(dsLocation); // call fits via irods rule for the locations Document fits = null; try { fits = runFITS(dsIrodsPath, dsAltIds); } catch (JDOMException e){ LOG.warn("Failed to parse FITS response", e); return null; } catch (Exception e) { throw new EnhancementException(e, Severity.UNRECOVERABLE); } // put the FITS document in DS map ds2FitsDoc.put(dsid, fits); } // build a PREMIS document Document premisTech = new Document(); Element p = new Element("premis", PREMIS_V2_NS); premisTech.addContent(p); for (String dsid : ds2FitsDoc.keySet()) { // get key PREMIS data Document fits = ds2FitsDoc.get(dsid); String md5checksum = fits.getRootElement().getChild("fileinfo", FITS_NS) .getChildText("md5checksum", FITS_NS); String size = fits.getRootElement().getChild("fileinfo", FITS_NS).getChildText("size", FITS_NS); // IDENTIFICATION LOGIC // get mimetype out of FITS XML Element trustedIdentity = null; Element idn = fits.getRootElement().getChild("identification", ns); for (Object child : idn.getChildren("identity", ns)) { Element el = (Element) child; if (idn.getAttributeValue("status") == null || el.getChildren("tool", ns).size() > 1 || (!"Exiftool".equals(el.getChild("tool", ns).getAttributeValue("toolname")) && !"application/x-symlink" .equals(el.getAttributeValue("mimetype")))) { trustedIdentity = el; break; } } String fitsMimetype = null; String format = null; if (trustedIdentity != null) { fitsMimetype = trustedIdentity.getAttributeValue("mimetype"); format = trustedIdentity.getAttributeValue("format"); } else { format = "Unknown"; LOG.warn("FITS unable to conclusively identify file: " + pid.getPID() + "/" + dsid); LOG.warn(new XMLOutputter().outputString(fits)); } if ("DATA_FILE".equals(dsid)) { if (fitsMimetype != null) { setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceMimeType.toString(), fitsMimetype, null); } else { // application/octet-stream setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceMimeType.toString(), "application/octet-stream", null); } try { Long.parseLong(size); setExclusiveTripleValue(pid.getPID(), ContentModelHelper.CDRProperty.hasSourceFileSize.toString(), size, "http://www.w3.org/2001/XMLSchema#long"); } catch (NumberFormatException e) { LOG.error("FITS produced a non-integer value for size: " + size); } } p.addContent(new Element("object", PREMIS_V2_NS) .addContent( new Element("objectIdentifier", PREMIS_V2_NS).addContent( new Element("objectIdentifierType", PREMIS_V2_NS).setText("Fedora Datastream PID")) .addContent(new Element("objectIdentifierValue", PREMIS_V2_NS).setText(dsid))) .addContent( new Element("objectCharacteristics", PREMIS_V2_NS) .addContent(new Element("compositionLevel", PREMIS_V2_NS).setText("0")) .addContent( new Element("fixity", PREMIS_V2_NS).addContent( new Element("messageDigestAlgorithm", PREMIS_V2_NS).setText("MD5")) .addContent(new Element("messageDigest", PREMIS_V2_NS).setText(md5checksum))) .addContent(new Element("size", PREMIS_V2_NS).setText(size)) .addContent( new Element("format", PREMIS_V2_NS).addContent(new Element("formatDesignation", PREMIS_V2_NS).addContent(new Element("formatName", PREMIS_V2_NS) .setText(format)))) .addContent( new Element("objectCharacteristicsExtension", PREMIS_V2_NS).addContent(ds2FitsDoc .get(dsid).detachRootElement()))) .setAttribute("type", PREMIS_V2_NS.getPrefix() + ":file", JDOMNamespaceUtil.XSI_NS)); } // upload tech MD PREMIS XML String premisTechURL = service.getManagementClient().upload(premisTech); // Add or replace the MD_TECHNICAL datastream for the object if (FOXMLJDOMUtil.getDatastream(foxml, ContentModelHelper.Datastream.MD_TECHNICAL.getName()) == null) { LOG.debug("Adding FITS output to MD_TECHNICAL"); //Ignore the add DS message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.ADD_DATASTREAM.toString(), null, ContentModelHelper.Datastream.MD_TECHNICAL.toString()); String message = "Adding technical metadata derived by FITS"; String newDSID = service.getManagementClient().addManagedDatastream(pid.getPID(), ContentModelHelper.Datastream.MD_TECHNICAL.getName(), false, message, new ArrayList<String>(), "PREMIS Technical Metadata", false, "text/xml", premisTechURL); } else { LOG.debug("Replacing MD_TECHNICAL with new FITS output"); //Ignore modify DS message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.MODIFY_DATASTREAM_BY_REFERENCE.toString(), null, ContentModelHelper.Datastream.MD_TECHNICAL.toString()); String message = "Replacing technical metadata derived by FITS"; service.getManagementClient().modifyDatastreamByReference(pid.getPID(), ContentModelHelper.Datastream.MD_TECHNICAL.getName(), false, message, new ArrayList<String>(), "PREMIS Technical Metadata", "text/xml", null, null, premisTechURL); } LOG.debug("Adding techData relationship"); PID newDSPID = new PID(pid.getPID().getPid() + "/" + ContentModelHelper.Datastream.MD_TECHNICAL.getName()); Map<String, List<String>> rels = service.getTripleStoreQueryService().fetchAllTriples(pid.getPID()); List<String> techrel = rels.get(ContentModelHelper.CDRProperty.techData.toString()); if (techrel == null || !techrel.contains(newDSPID.getURI())) { //Ignore the add relation message service.getServicesConductor().addSideEffect(pid.getPIDString(), JMSMessageUtil.FedoraActions.ADD_RELATIONSHIP.toString(), null, ContentModelHelper.CDRProperty.techData.toString()); service.getManagementClient().addObjectRelationship(pid.getPID(), ContentModelHelper.CDRProperty.techData.toString(), newDSPID); } LOG.debug("Finished MD_TECHNICAL updating for " + pid.getPID()); } catch (FileSystemException e) { throw new EnhancementException(e, Severity.FATAL); } catch (NotFoundException e) { throw new EnhancementException(e, Severity.UNRECOVERABLE); } catch (FedoraException e) { throw new EnhancementException(e, Severity.RECOVERABLE); } return result; }
diff --git a/src/org/omegat/gui/glossary/GlossaryReaderTBX.java b/src/org/omegat/gui/glossary/GlossaryReaderTBX.java index e91ec75e..ca4970c7 100644 --- a/src/org/omegat/gui/glossary/GlossaryReaderTBX.java +++ b/src/org/omegat/gui/glossary/GlossaryReaderTBX.java @@ -1,161 +1,165 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2010 Alex Buloichik, Didier Briel Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **************************************************************************/ package org.omegat.gui.glossary; import gen.core.tbx.LangSet; import gen.core.tbx.Martif; import gen.core.tbx.TermEntry; import gen.core.tbx.TermNote; import gen.core.tbx.Tig; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.omegat.core.Core; import org.omegat.util.Language; import org.omegat.util.OStrings; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; /** * Reader for TBX glossaries. * * @author Alex Buloichik <[email protected]> * @author Didier Briel */ public class GlossaryReaderTBX { protected static final JAXBContext TBX_CONTEXT; static { try { TBX_CONTEXT = JAXBContext.newInstance(Martif.class); } catch (Exception ex) { throw new ExceptionInInitializerError(OStrings .getString("STARTUP_JAXB_LINKAGE_ERROR")); } } static SAXParserFactory SAX_FACTORY = SAXParserFactory.newInstance(); static { SAX_FACTORY.setNamespaceAware(true); SAX_FACTORY.setValidating(false); } public static List<GlossaryEntry> read(final File file) throws Exception { Martif tbx = load(file); String sLang = Core.getProject().getProjectProperties() .getSourceLanguage().getLanguageCode(); String tLang = Core.getProject().getProjectProperties() .getTargetLanguage().getLanguageCode(); StringBuilder note = new StringBuilder(); List<GlossaryEntry> result = new ArrayList<GlossaryEntry>(); + List<String> sTerms = new ArrayList<String>(); + List<String> tTerms = new ArrayList<String>(); for (TermEntry te : tbx.getText().getBody().getTermEntry()) { - String sTerm = null; - String tTerm = null; note.setLength(0); for (LangSet ls : te.getLangSet()) { Language termLanguage = new Language(ls.getLang()); // We use only the language code String lang = termLanguage.getLanguageCode(); for (Object o : ls.getTigOrNtig()) { if (o instanceof Tig) { Tig t = (Tig) o; if (sLang.equalsIgnoreCase(lang)) { - sTerm = readContent(t.getTerm().getContent()); + sTerms.add(readContent(t.getTerm().getContent())); } else if (tLang.equalsIgnoreCase(lang)) { - tTerm = readContent(t.getTerm().getContent()); + tTerms.add(readContent(t.getTerm().getContent())); } for (TermNote tn : t.getTermNote()) { if (note.length() > 0) { note.append('\n'); } note.append(readContent(tn.getContent())); } } } } - if (sTerm != null && tTerm != null) { - result.add(new GlossaryEntry(sTerm, tTerm, note.toString())); + for (String s : sTerms) { + for (String t : tTerms) { + result.add(new GlossaryEntry(s, t, note.toString())); + } } + sTerms.clear(); + tTerms.clear(); } return result; } protected static String readContent(final List<Object> content) { StringBuilder res = new StringBuilder(); for (Object o : content) { res.append(o.toString()); } return res.toString(); } /** * Load tbx file, but skip DTD resolving. */ static Martif load(File f) throws Exception { Unmarshaller unm = TBX_CONTEXT.createUnmarshaller(); SAXParser parser = SAX_FACTORY.newSAXParser(); NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader()); xmlFilter.setContentHandler(unm.getUnmarshallerHandler()); FileInputStream in = new FileInputStream(f); try { SAXSource source = new SAXSource(xmlFilter, new InputSource(in)); return (Martif) unm.unmarshal(source); } finally { in.close(); } } public static class NamespaceFilter extends XMLFilterImpl { private static final InputSource EMPTY_INPUT_SOURCE = new InputSource( new ByteArrayInputStream(new byte[0])); public NamespaceFilter(XMLReader xmlReader) { super(xmlReader); } @Override public InputSource resolveEntity(String publicId, String systemId) { return EMPTY_INPUT_SOURCE; } } }
false
true
public static List<GlossaryEntry> read(final File file) throws Exception { Martif tbx = load(file); String sLang = Core.getProject().getProjectProperties() .getSourceLanguage().getLanguageCode(); String tLang = Core.getProject().getProjectProperties() .getTargetLanguage().getLanguageCode(); StringBuilder note = new StringBuilder(); List<GlossaryEntry> result = new ArrayList<GlossaryEntry>(); for (TermEntry te : tbx.getText().getBody().getTermEntry()) { String sTerm = null; String tTerm = null; note.setLength(0); for (LangSet ls : te.getLangSet()) { Language termLanguage = new Language(ls.getLang()); // We use only the language code String lang = termLanguage.getLanguageCode(); for (Object o : ls.getTigOrNtig()) { if (o instanceof Tig) { Tig t = (Tig) o; if (sLang.equalsIgnoreCase(lang)) { sTerm = readContent(t.getTerm().getContent()); } else if (tLang.equalsIgnoreCase(lang)) { tTerm = readContent(t.getTerm().getContent()); } for (TermNote tn : t.getTermNote()) { if (note.length() > 0) { note.append('\n'); } note.append(readContent(tn.getContent())); } } } } if (sTerm != null && tTerm != null) { result.add(new GlossaryEntry(sTerm, tTerm, note.toString())); } } return result; }
public static List<GlossaryEntry> read(final File file) throws Exception { Martif tbx = load(file); String sLang = Core.getProject().getProjectProperties() .getSourceLanguage().getLanguageCode(); String tLang = Core.getProject().getProjectProperties() .getTargetLanguage().getLanguageCode(); StringBuilder note = new StringBuilder(); List<GlossaryEntry> result = new ArrayList<GlossaryEntry>(); List<String> sTerms = new ArrayList<String>(); List<String> tTerms = new ArrayList<String>(); for (TermEntry te : tbx.getText().getBody().getTermEntry()) { note.setLength(0); for (LangSet ls : te.getLangSet()) { Language termLanguage = new Language(ls.getLang()); // We use only the language code String lang = termLanguage.getLanguageCode(); for (Object o : ls.getTigOrNtig()) { if (o instanceof Tig) { Tig t = (Tig) o; if (sLang.equalsIgnoreCase(lang)) { sTerms.add(readContent(t.getTerm().getContent())); } else if (tLang.equalsIgnoreCase(lang)) { tTerms.add(readContent(t.getTerm().getContent())); } for (TermNote tn : t.getTermNote()) { if (note.length() > 0) { note.append('\n'); } note.append(readContent(tn.getContent())); } } } } for (String s : sTerms) { for (String t : tTerms) { result.add(new GlossaryEntry(s, t, note.toString())); } } sTerms.clear(); tTerms.clear(); } return result; }